server-context.cpp 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619
  1. #include "server-context.h"
  2. #include "server-common.h"
  3. #include "server-http.h"
  4. #include "server-task.h"
  5. #include "server-queue.h"
  6. #include "arg.h"
  7. #include "common.h"
  8. #include "llama.h"
  9. #include "log.h"
  10. #include "sampling.h"
  11. #include "speculative.h"
  12. #include "mtmd.h"
  13. #include "mtmd-helper.h"
  14. #include <cstddef>
  15. #include <cinttypes>
  16. #include <memory>
  17. #include <unordered_set>
  18. // fix problem with std::min and std::max
  19. #if defined(_WIN32)
  20. #define WIN32_LEAN_AND_MEAN
  21. #ifndef NOMINMAX
  22. # define NOMINMAX
  23. #endif
  24. #include <windows.h>
  25. #endif
  26. using json = nlohmann::ordered_json;
  27. constexpr int HTTP_POLLING_SECONDS = 1;
  28. // state diagram: https://github.com/ggml-org/llama.cpp/pull/9283
  29. enum slot_state {
  30. SLOT_STATE_IDLE,
  31. SLOT_STATE_STARTED, // TODO: this state is only used for setting up the initial prompt processing; maybe merge it with launch_slot_with_task in the future
  32. SLOT_STATE_PROCESSING_PROMPT,
  33. SLOT_STATE_DONE_PROMPT,
  34. SLOT_STATE_GENERATING,
  35. };
  36. enum server_state {
  37. SERVER_STATE_LOADING_MODEL, // Server is starting up, model not fully loaded yet
  38. SERVER_STATE_READY, // Server is ready and model is loaded
  39. };
  40. static bool server_task_type_need_embd(server_task_type task_type) {
  41. switch (task_type) {
  42. case SERVER_TASK_TYPE_EMBEDDING:
  43. case SERVER_TASK_TYPE_RERANK:
  44. return true;
  45. default:
  46. return false;
  47. }
  48. }
  49. static bool server_task_type_need_logits(server_task_type task_type) {
  50. switch (task_type) {
  51. case SERVER_TASK_TYPE_COMPLETION:
  52. case SERVER_TASK_TYPE_INFILL:
  53. return true;
  54. default:
  55. return false;
  56. }
  57. }
  58. struct server_slot {
  59. int id;
  60. llama_batch batch_spec = {};
  61. // TODO: change to unique_ptrs for consistency:
  62. llama_context * ctx = nullptr;
  63. llama_context * ctx_dft = nullptr;
  64. // multimodal
  65. mtmd_context * mctx = nullptr;
  66. common_speculative * spec = nullptr;
  67. std::unique_ptr<const server_task> task;
  68. std::unique_ptr<const server_task> task_prev; // used for debugging
  69. // used to determine the slot that has been used the longest
  70. int64_t t_last_used = -1;
  71. // generation props
  72. int32_t n_ctx = 0; // context size per slot
  73. int32_t n_keep = 0;
  74. int32_t n_decoded = 0;
  75. int32_t n_remaining = -1;
  76. int32_t i_batch = -1;
  77. int32_t n_prompt_tokens_cache = 0;
  78. int32_t n_prompt_tokens_processed = 0;
  79. size_t last_nl_pos = 0;
  80. std::string generated_text;
  81. llama_tokens generated_tokens;
  82. common_chat_msg chat_msg;
  83. std::vector<completion_token_output> generated_token_probs;
  84. bool has_next_token = true;
  85. bool has_new_line = false;
  86. bool truncated = false;
  87. stop_type stop;
  88. std::string stopping_word;
  89. // state
  90. slot_state state = SLOT_STATE_IDLE;
  91. server_prompt prompt;
  92. void prompt_save(server_prompt_cache & prompt_cache) const {
  93. GGML_ASSERT(prompt.data.size() == 0);
  94. const size_t cur_size = llama_state_seq_get_size_ext(ctx, id, 0);
  95. SRV_WRN(" - saving prompt with length %d, total state size = %.3f MiB\n",
  96. (int) prompt.tokens.size(), cur_size / (1024.0 * 1024.0));
  97. auto * cur = prompt_cache.alloc(prompt, cur_size);
  98. if (cur == nullptr) {
  99. return;
  100. }
  101. llama_state_seq_get_data_ext(ctx, cur->data.data(), cur_size, id, 0);
  102. }
  103. bool prompt_load(server_prompt_cache & prompt_cache, const server_tokens & tokens) {
  104. bool res = prompt_cache.load(prompt, tokens, ctx, id);
  105. if (!res) {
  106. SLT_WRN(*this, "%s", "failed to load prompt from cache\n");
  107. }
  108. return res;
  109. }
  110. std::vector<common_adapter_lora_info> lora;
  111. int32_t alora_invocation_start = -1;
  112. // sampling
  113. json json_schema;
  114. struct common_sampler * smpl = nullptr;
  115. llama_token sampled;
  116. common_chat_format chat_format = COMMON_CHAT_FORMAT_CONTENT_ONLY;
  117. std::vector<std::string> generated_tool_call_ids;
  118. // stats
  119. size_t n_sent_text = 0; // number of sent text character
  120. int64_t t_start_process_prompt;
  121. int64_t t_start_generation;
  122. double t_prompt_processing; // ms
  123. double t_token_generation; // ms
  124. std::function<void(int)> callback_on_release;
  125. // Speculative decoding stats
  126. int32_t n_draft_total = 0; // Total draft tokens generated
  127. int32_t n_draft_accepted = 0; // Draft tokens actually accepted
  128. void reset() {
  129. SLT_DBG(*this, "%s", "\n");
  130. n_prompt_tokens_cache = 0;
  131. last_nl_pos = 0;
  132. generated_text = "";
  133. has_new_line = false;
  134. truncated = false;
  135. stop = STOP_TYPE_NONE;
  136. stopping_word = "";
  137. n_sent_text = 0;
  138. chat_format = COMMON_CHAT_FORMAT_CONTENT_ONLY;
  139. generated_tokens.clear();
  140. generated_token_probs.clear();
  141. chat_msg = {};
  142. json_schema = json();
  143. generated_tool_call_ids.clear();
  144. // clear speculative decoding stats
  145. n_draft_total = 0;
  146. n_draft_accepted = 0;
  147. task.reset();
  148. task_prev.reset();
  149. // clear alora start
  150. alora_invocation_start = -1;
  151. }
  152. bool need_embd() const {
  153. GGML_ASSERT(task);
  154. return server_task_type_need_embd(task->type);
  155. }
  156. bool need_logits() const {
  157. GGML_ASSERT(task);
  158. return server_task_type_need_logits(task->type);
  159. }
  160. // if the context does not have a memory module then all embeddings have to be computed within a single ubatch
  161. // also we cannot split if the pooling would require any past tokens
  162. bool can_split() const {
  163. return
  164. !need_embd() ||
  165. (llama_get_memory(ctx) && llama_pooling_type(ctx) == LLAMA_POOLING_TYPE_LAST);
  166. }
  167. bool can_batch_with(server_slot & other_slot) const {
  168. GGML_ASSERT(task);
  169. return task->type == other_slot.task->type && are_lora_equal(lora, other_slot.lora);
  170. }
  171. bool has_budget(const common_params & global_params) {
  172. GGML_ASSERT(task);
  173. if (task->params.n_predict == -1 && global_params.n_predict == -1) {
  174. return true; // limitless
  175. }
  176. n_remaining = -1;
  177. if (task->params.n_predict != -1) {
  178. n_remaining = task->params.n_predict - n_decoded;
  179. } else if (global_params.n_predict != -1) {
  180. n_remaining = global_params.n_predict - n_decoded;
  181. }
  182. return n_remaining > 0; // no budget
  183. }
  184. bool is_processing() const {
  185. return state != SLOT_STATE_IDLE;
  186. }
  187. bool can_speculate() const {
  188. return ctx_dft;
  189. }
  190. void add_token(const completion_token_output & token) {
  191. if (!is_processing()) {
  192. SLT_WRN(*this, "%s", "slot is not processing\n");
  193. return;
  194. }
  195. generated_token_probs.push_back(token);
  196. }
  197. void release() {
  198. if (is_processing()) {
  199. GGML_ASSERT(task);
  200. SLT_INF(*this, "stop processing: n_tokens = %d, truncated = %d\n", prompt.n_tokens(), truncated);
  201. t_last_used = ggml_time_us();
  202. t_token_generation = (ggml_time_us() - t_start_generation) / 1e3;
  203. state = SLOT_STATE_IDLE;
  204. task_prev = std::move(task);
  205. task.reset();
  206. callback_on_release(id);
  207. }
  208. }
  209. result_timings get_timings() const {
  210. result_timings timings;
  211. timings.cache_n = n_prompt_tokens_cache;
  212. timings.prompt_n = n_prompt_tokens_processed;
  213. timings.prompt_ms = t_prompt_processing;
  214. timings.prompt_per_token_ms = t_prompt_processing / n_prompt_tokens_processed;
  215. timings.prompt_per_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  216. timings.predicted_n = n_decoded;
  217. timings.predicted_ms = t_token_generation;
  218. timings.predicted_per_token_ms = t_token_generation / n_decoded;
  219. timings.predicted_per_second = 1e3 / t_token_generation * n_decoded;
  220. // Add speculative metrics
  221. if (n_draft_total > 0) {
  222. timings.draft_n = n_draft_total;
  223. timings.draft_n_accepted = n_draft_accepted;
  224. }
  225. return timings;
  226. }
  227. const common_chat_msg & update_chat_msg(std::vector<common_chat_msg_diff> & diffs) {
  228. GGML_ASSERT(task);
  229. auto previous_msg = chat_msg;
  230. SRV_DBG("Parsing chat message: %s\n", generated_text.c_str());
  231. auto new_msg = common_chat_parse(
  232. generated_text,
  233. /* is_partial= */ stop != STOP_TYPE_EOS,
  234. task->params.oaicompat_chat_syntax);
  235. if (!new_msg.empty()) {
  236. new_msg.set_tool_call_ids(generated_tool_call_ids, gen_tool_call_id);
  237. chat_msg = new_msg;
  238. diffs = common_chat_msg_diff::compute_diffs(previous_msg, new_msg.empty() ? previous_msg : new_msg);
  239. }
  240. return chat_msg;
  241. }
  242. size_t find_stopping_strings(const std::string & text, const size_t last_token_size, bool is_full_stop) {
  243. GGML_ASSERT(task);
  244. size_t stop_pos = std::string::npos;
  245. for (const std::string & word : task->params.antiprompt) {
  246. size_t pos;
  247. if (is_full_stop) {
  248. const size_t tmp = word.size() + last_token_size;
  249. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  250. pos = text.find(word, from_pos);
  251. } else {
  252. // otherwise, partial stop
  253. pos = string_find_partial_stop(text, word);
  254. }
  255. if (pos != std::string::npos && (stop_pos == std::string::npos || pos < stop_pos)) {
  256. if (is_full_stop) {
  257. stop = STOP_TYPE_WORD;
  258. stopping_word = word;
  259. has_next_token = false;
  260. }
  261. stop_pos = pos;
  262. }
  263. }
  264. return stop_pos;
  265. }
  266. void print_timings() const {
  267. const double t_prompt = t_prompt_processing / n_prompt_tokens_processed;
  268. const double n_prompt_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  269. const double t_gen = t_token_generation / n_decoded;
  270. const double n_gen_second = 1e3 / t_token_generation * n_decoded;
  271. SLT_INF(*this,
  272. "\n"
  273. "prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n"
  274. " eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n"
  275. " total time = %10.2f ms / %5d tokens\n",
  276. t_prompt_processing, n_prompt_tokens_processed, t_prompt, n_prompt_second,
  277. t_token_generation, n_decoded, t_gen, n_gen_second,
  278. t_prompt_processing + t_token_generation, n_prompt_tokens_processed + n_decoded);
  279. if (n_draft_total > 0) {
  280. const float draft_ratio = (float) n_draft_accepted / n_draft_total;
  281. SLT_INF(*this,
  282. "\n"
  283. "draft acceptance rate = %0.5f (%5d accepted / %5d generated)\n",
  284. draft_ratio, n_draft_accepted, n_draft_total
  285. );
  286. }
  287. }
  288. json to_json(bool only_metrics = false) const {
  289. json res;
  290. res = {
  291. {"id", id},
  292. {"n_ctx", n_ctx},
  293. {"speculative", can_speculate()},
  294. {"is_processing", is_processing()},
  295. };
  296. const auto & ptask = task ? task : task_prev;
  297. if (ptask) {
  298. res["id_task"] = ptask->id;
  299. res["params"] = ptask->params.to_json(only_metrics);
  300. res["next_token"] = {
  301. {
  302. {"has_next_token", has_next_token},
  303. {"has_new_line", has_new_line},
  304. {"n_remain", n_remaining},
  305. {"n_decoded", n_decoded},
  306. }
  307. };
  308. if (!only_metrics) {
  309. res["prompt"] = ptask->tokens.detokenize(ctx, true);
  310. res["generated"] = generated_text;
  311. }
  312. }
  313. return res;
  314. }
  315. };
  316. //
  317. // server_metrics
  318. //
  319. struct server_metrics {
  320. int64_t t_start = 0;
  321. uint64_t n_prompt_tokens_processed_total = 0;
  322. uint64_t t_prompt_processing_total = 0;
  323. uint64_t n_tokens_predicted_total = 0;
  324. uint64_t t_tokens_generation_total = 0;
  325. uint64_t n_tokens_max = 0;
  326. uint64_t n_prompt_tokens_processed = 0;
  327. uint64_t t_prompt_processing = 0;
  328. uint64_t n_tokens_predicted = 0;
  329. uint64_t t_tokens_generation = 0;
  330. uint64_t n_decode_total = 0;
  331. uint64_t n_busy_slots_total = 0;
  332. void init() {
  333. t_start = ggml_time_us();
  334. }
  335. void on_prompt_eval(const server_slot & slot) {
  336. n_prompt_tokens_processed_total += slot.n_prompt_tokens_processed;
  337. n_prompt_tokens_processed += slot.n_prompt_tokens_processed;
  338. t_prompt_processing += slot.t_prompt_processing;
  339. t_prompt_processing_total += slot.t_prompt_processing;
  340. n_tokens_max = std::max(n_tokens_max, (uint64_t) slot.prompt.n_tokens());
  341. }
  342. void on_prediction(const server_slot & slot) {
  343. n_tokens_predicted_total += slot.n_decoded;
  344. n_tokens_predicted += slot.n_decoded;
  345. t_tokens_generation += slot.t_token_generation;
  346. t_tokens_generation_total += slot.t_token_generation;
  347. }
  348. void on_decoded(const std::vector<server_slot> & slots) {
  349. n_decode_total++;
  350. for (const auto & slot : slots) {
  351. if (slot.is_processing()) {
  352. n_busy_slots_total++;
  353. }
  354. n_tokens_max = std::max(n_tokens_max, (uint64_t) slot.prompt.n_tokens());
  355. }
  356. }
  357. void reset_bucket() {
  358. n_prompt_tokens_processed = 0;
  359. t_prompt_processing = 0;
  360. n_tokens_predicted = 0;
  361. t_tokens_generation = 0;
  362. }
  363. };
  364. //
  365. // server_context_impl (private implementation)
  366. //
  367. struct server_context_impl {
  368. common_params params_base;
  369. // note: keep these alive - they determine the lifetime of the model, context, etc.
  370. common_init_result llama_init;
  371. common_init_result llama_init_dft;
  372. llama_model * model = nullptr;
  373. llama_context * ctx = nullptr;
  374. // multimodal
  375. mtmd_context * mctx = nullptr;
  376. const llama_vocab * vocab = nullptr;
  377. bool vocab_dft_compatible = true;
  378. llama_model * model_dft = nullptr;
  379. llama_context_params cparams_dft;
  380. llama_batch batch {};
  381. bool add_bos_token = true;
  382. int32_t n_ctx; // total context for all clients / slots
  383. // slots / clients
  384. std::vector<server_slot> slots;
  385. int slots_debug = 0;
  386. server_queue queue_tasks;
  387. server_response queue_results;
  388. std::unique_ptr<server_prompt_cache> prompt_cache;
  389. server_metrics metrics;
  390. // Necessary similarity of prompt for slot selection
  391. float slot_prompt_similarity = 0.0f;
  392. common_chat_templates_ptr chat_templates;
  393. oaicompat_parser_options oai_parser_opt;
  394. ~server_context_impl() {
  395. mtmd_free(mctx);
  396. // Clear any sampling context
  397. for (server_slot & slot : slots) {
  398. common_sampler_free(slot.smpl);
  399. slot.smpl = nullptr;
  400. llama_free(slot.ctx_dft);
  401. slot.ctx_dft = nullptr;
  402. common_speculative_free(slot.spec);
  403. slot.spec = nullptr;
  404. llama_batch_free(slot.batch_spec);
  405. }
  406. llama_batch_free(batch);
  407. }
  408. // load the model and initialize llama_context
  409. bool load_model(const common_params & params) {
  410. SRV_INF("loading model '%s'\n", params.model.path.c_str());
  411. params_base = params;
  412. llama_init = common_init_from_params(params_base);
  413. model = llama_init.model.get();
  414. ctx = llama_init.context.get();
  415. if (model == nullptr) {
  416. SRV_ERR("failed to load model, '%s'\n", params_base.model.path.c_str());
  417. return false;
  418. }
  419. vocab = llama_model_get_vocab(model);
  420. n_ctx = llama_n_ctx(ctx);
  421. add_bos_token = llama_vocab_get_add_bos(vocab);
  422. if (params_base.has_speculative()) {
  423. SRV_INF("loading draft model '%s'\n", params_base.speculative.model.path.c_str());
  424. auto params_dft = params_base;
  425. params_dft.devices = params_base.speculative.devices;
  426. params_dft.model = params_base.speculative.model;
  427. params_dft.n_ctx = params_base.speculative.n_ctx == 0 ? llama_n_ctx_seq(ctx) : params_base.speculative.n_ctx;
  428. params_dft.n_gpu_layers = params_base.speculative.n_gpu_layers;
  429. params_dft.n_parallel = 1;
  430. params_dft.cache_type_k = params_base.speculative.cache_type_k;
  431. params_dft.cache_type_v = params_base.speculative.cache_type_v;
  432. params_dft.cpuparams.n_threads = params_base.speculative.cpuparams.n_threads;
  433. params_dft.cpuparams_batch.n_threads = params_base.speculative.cpuparams_batch.n_threads;
  434. params_dft.tensor_buft_overrides = params_base.speculative.tensor_buft_overrides;
  435. llama_init_dft = common_init_from_params(params_dft);
  436. model_dft = llama_init_dft.model.get();
  437. if (model_dft == nullptr) {
  438. SRV_ERR("failed to load draft model, '%s'\n", params_base.speculative.model.path.c_str());
  439. return false;
  440. }
  441. vocab_dft_compatible = common_speculative_are_compatible(ctx, llama_init_dft.context.get());
  442. if (!vocab_dft_compatible) {
  443. SRV_INF("the draft model '%s' is not compatible with the target model '%s'. tokens will be translated between the draft and target models.\n", params_base.speculative.model.path.c_str(), params_base.model.path.c_str());
  444. }
  445. const int n_ctx_dft = llama_n_ctx(llama_init_dft.context.get());
  446. cparams_dft = common_context_params_to_llama(params_dft);
  447. cparams_dft.n_batch = n_ctx_dft;
  448. // the context is not needed - we will create one for each slot
  449. llama_init_dft.context.reset();
  450. }
  451. chat_templates = common_chat_templates_init(model, params_base.chat_template);
  452. try {
  453. common_chat_format_example(chat_templates.get(), params.use_jinja, params.default_template_kwargs);
  454. } catch (const std::exception & e) {
  455. SRV_WRN("%s: Chat template parsing error: %s\n", __func__, e.what());
  456. SRV_WRN("%s: The chat template that comes with this model is not yet supported, falling back to chatml. This may cause the model to output suboptimal responses\n", __func__);
  457. chat_templates = common_chat_templates_init(model, "chatml");
  458. }
  459. std::string & mmproj_path = params_base.mmproj.path;
  460. if (!mmproj_path.empty()) {
  461. mtmd_helper_log_set(common_log_default_callback, nullptr);
  462. mtmd_context_params mparams = mtmd_context_params_default();
  463. mparams.use_gpu = params_base.mmproj_use_gpu;
  464. mparams.print_timings = false;
  465. mparams.n_threads = params_base.cpuparams.n_threads;
  466. mparams.flash_attn_type = params_base.flash_attn_type;
  467. mparams.image_min_tokens = params_base.image_min_tokens;
  468. mparams.image_max_tokens = params_base.image_max_tokens;
  469. mctx = mtmd_init_from_file(mmproj_path.c_str(), model, mparams);
  470. if (mctx == nullptr) {
  471. SRV_ERR("failed to load multimodal model, '%s'\n", mmproj_path.c_str());
  472. return false;
  473. }
  474. SRV_INF("loaded multimodal model, '%s'\n", mmproj_path.c_str());
  475. if (params_base.ctx_shift) {
  476. params_base.ctx_shift = false;
  477. SRV_WRN("%s\n", "ctx_shift is not supported by multimodal, it will be disabled");
  478. }
  479. if (params_base.n_cache_reuse) {
  480. params_base.n_cache_reuse = 0;
  481. SRV_WRN("%s\n", "cache_reuse is not supported by multimodal, it will be disabled");
  482. }
  483. if (params_base.has_speculative()) {
  484. SRV_ERR("%s\n", "err: speculative decode is not supported by multimodal");
  485. return false;
  486. }
  487. }
  488. if (!llama_memory_can_shift(llama_get_memory(ctx))) {
  489. if (params_base.ctx_shift) {
  490. params_base.ctx_shift = false;
  491. SRV_WRN("%s\n", "ctx_shift is not supported by this context, it will be disabled");
  492. }
  493. if (params_base.n_cache_reuse) {
  494. params_base.n_cache_reuse = 0;
  495. SRV_WRN("%s\n", "cache_reuse is not supported by this context, it will be disabled");
  496. }
  497. }
  498. return true;
  499. }
  500. // initialize slots and server-related data
  501. void init() {
  502. // wiring up server queues
  503. queue_tasks.on_new_task([this](server_task && task) {
  504. process_single_task(std::move(task));
  505. });
  506. queue_tasks.on_update_slots([this]() {
  507. update_slots();
  508. });
  509. // Necessary similarity of prompt for slot selection
  510. slot_prompt_similarity = params_base.slot_prompt_similarity;
  511. // setup slots
  512. SRV_INF("initializing slots, n_slots = %d\n", params_base.n_parallel);
  513. const int n_ctx_train = llama_model_n_ctx_train(model);
  514. int n_ctx_slot = llama_n_ctx_seq(ctx);
  515. if (n_ctx_slot > n_ctx_train) {
  516. SRV_WRN("the slot context (%d) exceeds the training context of the model (%d) - capping\n", n_ctx_slot, n_ctx_train);
  517. n_ctx_slot = n_ctx_train;
  518. }
  519. for (int i = 0; i < params_base.n_parallel; i++) {
  520. server_slot slot;
  521. slot.id = i;
  522. slot.ctx = ctx;
  523. slot.n_ctx = n_ctx_slot;
  524. slot.mctx = mctx;
  525. slot.prompt.tokens.has_mtmd = mctx != nullptr;
  526. if (model_dft) {
  527. slot.batch_spec = llama_batch_init(params_base.speculative.n_max + 1, 0, 1);
  528. // TODO: rework speculative decoding [TAG_SERVER_SPEC_REWORK]
  529. slot.ctx_dft = llama_init_from_model(model_dft, cparams_dft);
  530. if (slot.ctx_dft == nullptr) {
  531. SRV_ERR("%s", "failed to create draft context\n");
  532. return;
  533. }
  534. slot.spec = common_speculative_init(slot.ctx, slot.ctx_dft);
  535. if (slot.spec == nullptr) {
  536. SRV_ERR("%s", "failed to create speculator\n");
  537. return;
  538. }
  539. for (auto & pair : params_base.speculative.replacements) {
  540. common_speculative_add_replacement_tgt_dft(slot.spec, pair.first.c_str(), pair.second.c_str());
  541. }
  542. }
  543. SLT_INF(slot, "new slot, n_ctx = %d\n", slot.n_ctx);
  544. slot.callback_on_release = [this](int) {
  545. queue_tasks.pop_deferred_task();
  546. };
  547. slot.reset();
  548. slots.push_back(std::move(slot));
  549. }
  550. {
  551. const char * LLAMA_SERVER_SLOTS_DEBUG = getenv("LLAMA_SERVER_SLOTS_DEBUG");
  552. slots_debug = LLAMA_SERVER_SLOTS_DEBUG ? atoi(LLAMA_SERVER_SLOTS_DEBUG) : 0;
  553. if (slots_debug) {
  554. SRV_WRN("slots debug = %d\n", slots_debug);
  555. }
  556. }
  557. // the update_slots() logic will always submit a maximum of n_batch or n_parallel tokens
  558. // note that n_batch can be > n_ctx (e.g. for non-causal attention models such as BERT where the KV cache is not used)
  559. {
  560. const int32_t n_batch = llama_n_batch(ctx);
  561. batch = llama_batch_init(std::max(n_batch, params_base.n_parallel), 0, 1);
  562. }
  563. metrics.init();
  564. if (params_base.cache_ram_mib != 0) {
  565. if (params_base.cache_ram_mib < 0) {
  566. SRV_WRN("prompt cache is enabled, size limit: %s\n", "no limit");
  567. } else {
  568. SRV_WRN("prompt cache is enabled, size limit: %d MiB\n", params_base.cache_ram_mib);
  569. }
  570. SRV_WRN("%s", "use `--cache-ram 0` to disable the prompt cache\n");
  571. prompt_cache = std::make_unique<server_prompt_cache>(params_base.cache_ram_mib, n_ctx);
  572. } else {
  573. SRV_WRN("%s", "prompt cache is disabled - use `--cache-ram N` to enable it\n");
  574. }
  575. SRV_WRN("%s", "for more info see https://github.com/ggml-org/llama.cpp/pull/16391\n");
  576. // thinking is enabled if:
  577. // 1. It's not explicitly disabled (reasoning_budget == 0)
  578. // 2. The chat template supports it
  579. const bool enable_thinking = params_base.use_jinja && params_base.reasoning_budget != 0 && common_chat_templates_support_enable_thinking(chat_templates.get());
  580. SRV_INF("thinking = %d\n", enable_thinking);
  581. oai_parser_opt = {
  582. /* use_jinja */ params_base.use_jinja,
  583. /* prefill_assistant */ params_base.prefill_assistant,
  584. /* reasoning_format */ params_base.reasoning_format,
  585. /* chat_template_kwargs */ params_base.default_template_kwargs,
  586. /* common_chat_templates */ chat_templates.get(),
  587. /* allow_image */ mctx ? mtmd_support_vision(mctx) : false,
  588. /* allow_audio */ mctx ? mtmd_support_audio (mctx) : false,
  589. /* enable_thinking */ enable_thinking,
  590. };
  591. // print sample chat example to make it clear which template is used
  592. LOG_INF("%s: chat template, chat_template: %s, example_format: '%s'\n", __func__,
  593. common_chat_templates_source(chat_templates.get()),
  594. common_chat_format_example(chat_templates.get(), params_base.use_jinja, params_base.default_template_kwargs).c_str());
  595. }
  596. server_slot * get_slot_by_id(int id) {
  597. for (server_slot & slot : slots) {
  598. if (slot.id == id) {
  599. return &slot;
  600. }
  601. }
  602. return nullptr;
  603. }
  604. server_slot * get_available_slot(const server_task & task) {
  605. server_slot * ret = nullptr;
  606. bool update_cache = false;
  607. // find the slot that has at least n% prompt similarity
  608. if (ret == nullptr && slot_prompt_similarity != 0.0f) {
  609. float sim_best = 0;
  610. for (server_slot & slot : slots) {
  611. // skip the slot if it is not available
  612. if (slot.is_processing()) {
  613. continue;
  614. }
  615. const auto & tokens = slot.prompt.tokens;
  616. // skip the slot if it does not contains cached tokens
  617. if (tokens.empty()) {
  618. continue;
  619. }
  620. // fraction of the Longest Common Prefix length with respect to the input prompt length
  621. const float sim_cur = float(tokens.get_common_prefix(task.tokens)) / task.tokens.size();
  622. // select the current slot if the criteria match
  623. if (sim_cur > sim_best && sim_cur > slot_prompt_similarity) {
  624. sim_best = sim_cur;
  625. ret = &slot;
  626. }
  627. }
  628. if (ret != nullptr) {
  629. const float f_keep = (sim_best*task.tokens.size()) / ret->prompt.tokens.size();
  630. SLT_INF(*ret, "selected slot by LCP similarity, sim_best = %.3f (> %.3f thold), f_keep = %.3f\n",
  631. sim_best, slot_prompt_similarity, f_keep);
  632. // if we are about to lose a large portion of the existing context - save it in the prompt cache
  633. if (f_keep < 0.5f) {
  634. update_cache = true;
  635. }
  636. }
  637. }
  638. // find the slot that has been least recently used
  639. if (ret == nullptr) {
  640. int64_t t_last = -1;
  641. for (server_slot & slot : slots) {
  642. // skip the slot if it is not available
  643. if (slot.is_processing()) {
  644. continue;
  645. }
  646. // select the current slot if the criteria match
  647. if (!ret || slot.t_last_used <= t_last) {
  648. t_last = slot.t_last_used;
  649. ret = &slot;
  650. }
  651. }
  652. if (ret != nullptr) {
  653. SLT_INF(*ret, "selected slot by LRU, t_last = %" PRId64 "\n", t_last);
  654. update_cache = true;
  655. }
  656. }
  657. if (ret) {
  658. const auto & tokens = ret->prompt.tokens;
  659. update_cache = update_cache && prompt_cache;
  660. // cache prompts only for completion tasks
  661. update_cache = update_cache && task.type == SERVER_TASK_TYPE_COMPLETION;
  662. // don't update the cache if the slot's context is empty
  663. update_cache = update_cache && tokens.size() > 0;
  664. // TODO: mtmd does not support prompt cache
  665. update_cache = update_cache && (ret->mctx == nullptr);
  666. if (update_cache) {
  667. SRV_WRN("%s", "updating prompt cache\n");
  668. const int64_t t_start = ggml_time_us();
  669. ret->prompt_save(*prompt_cache);
  670. if (!ret->prompt_load(*prompt_cache, task.tokens)) {
  671. clear_slot(*ret);
  672. }
  673. prompt_cache->update();
  674. SRV_WRN("prompt cache update took %.2f ms\n", (ggml_time_us() - t_start) / 1000.0);
  675. }
  676. }
  677. return ret;
  678. }
  679. void clear_slot(server_slot & slot) const {
  680. GGML_ASSERT(!slot.is_processing());
  681. SLT_WRN(slot, "clearing slot with %zu tokens\n", slot.prompt.tokens.size());
  682. llama_memory_seq_rm(llama_get_memory(ctx), slot.id, -1, -1);
  683. slot.prompt.tokens.clear();
  684. }
  685. // return true if at least one slot has been cleared
  686. // TODO: improve logic
  687. // - smarter decision which slot to clear (LRU or longest prompt?)
  688. // - move slot to level 2 cache instead of removing?
  689. // - instead of purging, try to store and resume later?
  690. bool try_clear_idle_slots() {
  691. bool res = false;
  692. if (!params_base.kv_unified) {
  693. return res;
  694. }
  695. for (auto & slot : slots) {
  696. if (slot.is_processing()) {
  697. continue;
  698. }
  699. if (slot.prompt.n_tokens() > 0) {
  700. SRV_WRN("purging slot %d with %zu tokens\n", slot.id, slot.prompt.tokens.size());
  701. clear_slot(slot);
  702. res = true;
  703. // clear slots one by one
  704. break;
  705. }
  706. }
  707. return res;
  708. }
  709. bool launch_slot_with_task(server_slot & slot, server_task && task) {
  710. slot.reset();
  711. if (!are_lora_equal(task.params.lora, slot.lora)) {
  712. // if lora has changed, check to see if the cache should be cleared
  713. if (lora_should_clear_cache(slot.lora, task.params.lora)) {
  714. SLT_INF(slot, "clearing cache for lora change. %zu loras -> %zu loras\n", slot.lora.size(), task.params.lora.size());
  715. slot.prompt.tokens.clear();
  716. } else {
  717. SLT_INF(slot, "keeping cache for alora. %zu target loras\n", task.params.lora.size());
  718. }
  719. slot.lora = task.params.lora;
  720. }
  721. // if using alora, make sure it's only a single one requested and active
  722. size_t alora_invocation_start = task.tokens.size();
  723. if (lora_all_alora(slot.lora)) {
  724. const auto & enabled_ids = lora_get_enabled_ids(slot.lora);
  725. // TODO: This will error out if a user requests two aloras, but only
  726. // provides the activation string for one. We could, instead search
  727. // for all requested alora activation strings and then either keep
  728. // only the last one, or reject if multiple are found.
  729. if (enabled_ids.size() != 1) {
  730. send_error(task, "Cannot run multiple aLoRAs in a single request", ERROR_TYPE_INVALID_REQUEST);
  731. return false;
  732. }
  733. const auto & lora = slot.lora[enabled_ids[0]].ptr;
  734. // get the pointer and count for the invocation tokens
  735. const uint64_t n_invocation_tokens = llama_adapter_get_alora_n_invocation_tokens(lora);
  736. const llama_token * invocation_tokens = llama_adapter_get_alora_invocation_tokens (lora);
  737. // scan backwards through the prompt tokens to find the last
  738. // occurrence of the invocation sequence
  739. int match_idx = static_cast<int>(n_invocation_tokens) - 1;
  740. for (int i = task.tokens.size() - 1; i >= 0; --i) {
  741. // the token in this position matches the next token to find in
  742. // the invocation sequence
  743. if (task.tokens[i] == invocation_tokens[match_idx]) {
  744. // if it's a full match, we've found the start
  745. if (match_idx == 0) {
  746. alora_invocation_start = i;
  747. break;
  748. }
  749. // otherwise, check the next token in the sequence
  750. --match_idx;
  751. } else {
  752. // no match in this position, so start looking over again
  753. match_idx = static_cast<int>(n_invocation_tokens) - 1;
  754. }
  755. }
  756. // if the activation string is not found, disable the alora
  757. if (alora_invocation_start == task.tokens.size()) {
  758. SLT_DBG(slot, "alora %zu requested, but not found. deactivating\n", enabled_ids[0]);
  759. slot.lora[enabled_ids[0]].scale = 0.0f;
  760. } else {
  761. SLT_DBG(slot, "alora %zu activated starting at %zu\n", enabled_ids[0], alora_invocation_start);
  762. slot.alora_invocation_start = alora_invocation_start;
  763. }
  764. }
  765. if (!task.tokens.validate(ctx)) {
  766. send_error(task, "Prompt contains invalid tokens", ERROR_TYPE_INVALID_REQUEST);
  767. return false;
  768. }
  769. SLT_DBG(slot, "launching slot : %s\n", safe_json_to_str(slot.to_json()).c_str());
  770. // initialize samplers
  771. {
  772. if (slot.smpl != nullptr) {
  773. common_sampler_free(slot.smpl);
  774. }
  775. slot.smpl = common_sampler_init(model, task.params.sampling);
  776. if (slot.smpl == nullptr) {
  777. // for now, the only error that may happen here is invalid grammar
  778. send_error(task, "Failed to parse grammar", ERROR_TYPE_INVALID_REQUEST);
  779. return false;
  780. }
  781. SLT_INF(slot, "sampler chain: %s\n", common_sampler_print(slot.smpl).c_str());
  782. }
  783. // initialize draft batch
  784. // TODO: rework speculative decoding [TAG_SERVER_SPEC_REWORK]
  785. if (slot.ctx_dft) {
  786. llama_batch_free(slot.batch_spec);
  787. slot.batch_spec = llama_batch_init(task.params.speculative.n_max + 1, 0, 1);
  788. }
  789. slot.task = std::make_unique<const server_task>(std::move(task));
  790. slot.state = SLOT_STATE_STARTED;
  791. SLT_INF(slot, "%s", "processing task\n");
  792. return true;
  793. }
  794. bool process_token(completion_token_output & result, server_slot & slot) {
  795. // remember which tokens were sampled - used for repetition penalties during sampling
  796. const std::string token_str = result.text_to_send;
  797. slot.sampled = result.tok;
  798. slot.generated_text += token_str;
  799. if (slot.task->params.return_tokens) {
  800. slot.generated_tokens.push_back(result.tok);
  801. }
  802. slot.has_next_token = true;
  803. // check if there is incomplete UTF-8 character at the end
  804. bool incomplete = validate_utf8(slot.generated_text) < slot.generated_text.size();
  805. // search stop word and delete it
  806. if (!incomplete) {
  807. size_t pos = std::min(slot.n_sent_text, slot.generated_text.size());
  808. const std::string str_test = slot.generated_text.substr(pos);
  809. bool send_text = true;
  810. size_t stop_pos = slot.find_stopping_strings(str_test, token_str.size(), true);
  811. if (stop_pos != std::string::npos) {
  812. slot.generated_text.erase(
  813. slot.generated_text.begin() + pos + stop_pos,
  814. slot.generated_text.end());
  815. pos = std::min(slot.n_sent_text, slot.generated_text.size());
  816. } else if (slot.has_next_token && !llama_vocab_is_eog(vocab, result.tok) ) {
  817. stop_pos = slot.find_stopping_strings(str_test, token_str.size(), false);
  818. send_text = stop_pos == std::string::npos;
  819. }
  820. // check if there is any token to predict
  821. if (send_text) {
  822. // no send the stop word in the response
  823. result.text_to_send = slot.generated_text.substr(pos, std::string::npos);
  824. slot.n_sent_text += result.text_to_send.size();
  825. // add the token to slot queue and cache
  826. } else {
  827. result.text_to_send = "";
  828. }
  829. slot.add_token(result);
  830. if (slot.task->params.stream) {
  831. send_partial_response(slot, result, false);
  832. }
  833. }
  834. if (incomplete) {
  835. slot.has_next_token = true;
  836. }
  837. // if context shifting is disabled, make sure that we don't run out of context
  838. if (!params_base.ctx_shift && slot.prompt.n_tokens() + 1 >= slot.n_ctx) {
  839. slot.truncated = true;
  840. slot.stop = STOP_TYPE_LIMIT;
  841. slot.has_next_token = false;
  842. SLT_DBG(slot, "stopped due to running out of context capacity, prompt.n_tokens() = %d, task.n_tokens = %d, n_decoded = %d, n_ctx = %d\n",
  843. slot.prompt.n_tokens(), slot.task->n_tokens(), slot.n_decoded, slot.n_ctx);
  844. }
  845. // check the limits
  846. if (slot.n_decoded > 0 && slot.has_next_token && !slot.has_budget(params_base)) {
  847. slot.stop = STOP_TYPE_LIMIT;
  848. slot.has_next_token = false;
  849. SLT_DBG(slot, "stopped by limit, n_decoded = %d, n_predict = %d\n", slot.n_decoded, slot.task->params.n_predict);
  850. }
  851. if (slot.has_new_line) {
  852. // require that each new line has a whitespace prefix (i.e. indentation) of at least slot.params.n_indent
  853. if (slot.task->params.n_indent > 0) {
  854. // check the current indentation
  855. // TODO: improve by not doing it more than once for each new line
  856. if (slot.last_nl_pos > 0) {
  857. size_t pos = slot.last_nl_pos;
  858. int n_indent = 0;
  859. while (pos < slot.generated_text.size() && (slot.generated_text[pos] == ' ' || slot.generated_text[pos] == '\t')) {
  860. n_indent++;
  861. pos++;
  862. }
  863. if (pos < slot.generated_text.size() && n_indent < slot.task->params.n_indent) {
  864. slot.stop = STOP_TYPE_LIMIT;
  865. slot.has_next_token = false;
  866. // cut the last line
  867. slot.generated_text.erase(pos, std::string::npos);
  868. SLT_DBG(slot, "stopped by indentation limit, n_decoded = %d, n_indent = %d\n", slot.n_decoded, n_indent);
  869. }
  870. }
  871. // find the next new line
  872. {
  873. const size_t pos = slot.generated_text.find('\n', slot.last_nl_pos);
  874. if (pos != std::string::npos) {
  875. slot.last_nl_pos = pos + 1;
  876. }
  877. }
  878. }
  879. }
  880. // check if there is a new line in the generated text
  881. if (result.text_to_send.find('\n') != std::string::npos) {
  882. slot.has_new_line = true;
  883. // if we have seen a new line, we stop after a certain time limit, but only upon another new line
  884. if (slot.task->params.t_max_predict_ms > 0 && (ggml_time_us() - slot.t_start_generation > 1000.0f*slot.task->params.t_max_predict_ms)) {
  885. slot.stop = STOP_TYPE_LIMIT;
  886. slot.has_next_token = false;
  887. SLT_DBG(slot, "stopped by time limit, n_decoded = %d, t_max_predict_ms = %d ms\n", slot.n_decoded, (int) slot.task->params.t_max_predict_ms);
  888. }
  889. }
  890. if (llama_vocab_is_eog(vocab, result.tok)) {
  891. slot.stop = STOP_TYPE_EOS;
  892. slot.has_next_token = false;
  893. SLT_DBG(slot, "%s", "stopped by EOS\n");
  894. }
  895. SLT_DBG(slot, "n_decoded = %d, n_remaining = %d, next token: %5d '%s'\n", slot.n_decoded, slot.n_remaining, result.tok, token_str.c_str());
  896. return slot.has_next_token; // continue
  897. }
  898. void populate_token_probs(const server_slot & slot, completion_token_output & result, bool post_sampling, bool special, int idx) const {
  899. size_t n_probs = slot.task->params.sampling.n_probs;
  900. size_t n_vocab = llama_vocab_n_tokens(vocab);
  901. if (post_sampling) {
  902. const auto * cur_p = common_sampler_get_candidates(slot.smpl, true);
  903. const size_t max_probs = cur_p->size;
  904. // set probability for sampled token
  905. for (size_t i = 0; i < max_probs; i++) {
  906. if (cur_p->data[i].id == result.tok) {
  907. result.prob = cur_p->data[i].p;
  908. break;
  909. }
  910. }
  911. // set probability for top n_probs tokens
  912. result.probs.reserve(max_probs);
  913. for (size_t i = 0; i < std::min(max_probs, n_probs); i++) {
  914. result.probs.push_back({
  915. cur_p->data[i].id,
  916. common_token_to_piece(ctx, cur_p->data[i].id, special),
  917. cur_p->data[i].p
  918. });
  919. }
  920. } else {
  921. // TODO: optimize this with min-p optimization
  922. std::vector<llama_token_data> cur = get_token_probabilities(ctx, idx);
  923. // set probability for sampled token
  924. for (size_t i = 0; i < n_vocab; i++) {
  925. // set probability for sampled token
  926. if (cur[i].id == result.tok) {
  927. result.prob = cur[i].p;
  928. break;
  929. }
  930. }
  931. // set probability for top n_probs tokens
  932. result.probs.reserve(n_probs);
  933. for (size_t i = 0; i < std::min(n_vocab, n_probs); i++) {
  934. result.probs.push_back({
  935. cur[i].id,
  936. common_token_to_piece(ctx, cur[i].id, special),
  937. cur[i].p
  938. });
  939. }
  940. }
  941. }
  942. void send_error(const server_task & task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  943. send_error(task.id, error, type);
  944. }
  945. void send_error(const server_slot & slot, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  946. send_error(slot.task->id, error, type, slot.task->n_tokens(), slot.n_ctx);
  947. }
  948. void send_error(const int id_task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER, const int32_t n_prompt_tokens = 0, const int32_t n_ctx = 0) {
  949. SRV_ERR("task id = %d, error: %s\n", id_task, error.c_str());
  950. if (type == ERROR_TYPE_EXCEED_CONTEXT_SIZE) {
  951. GGML_ASSERT(n_ctx > 0 && n_prompt_tokens > 0);
  952. }
  953. auto res = std::make_unique<server_task_result_error>();
  954. res->id = id_task;
  955. res->err_type = type;
  956. res->err_msg = error;
  957. res->n_prompt_tokens = n_prompt_tokens;
  958. res->n_ctx = n_ctx;
  959. queue_results.send(std::move(res));
  960. }
  961. // if multimodal is enabled, send an error and return false
  962. bool check_no_mtmd(const int id_task) {
  963. if (mctx) {
  964. send_error(id_task, "This feature is not supported by multimodal", ERROR_TYPE_NOT_SUPPORTED);
  965. return false;
  966. }
  967. return true;
  968. }
  969. void send_partial_response(server_slot & slot, const completion_token_output & tkn, bool is_progress) {
  970. auto res = std::make_unique<server_task_result_cmpl_partial>();
  971. res->id = slot.task->id;
  972. res->index = slot.task->index;
  973. if (is_progress) {
  974. res->is_progress = true;
  975. res->progress.total = slot.task->n_tokens();
  976. res->progress.cache = slot.n_prompt_tokens_cache;
  977. res->progress.processed = slot.prompt.tokens.size();
  978. res->progress.time_ms = (ggml_time_us() - slot.t_start_process_prompt) / 1000;
  979. } else {
  980. res->content = tkn.text_to_send;
  981. res->tokens = { tkn.tok };
  982. slot.update_chat_msg(res->oaicompat_msg_diffs);
  983. }
  984. res->n_decoded = slot.n_decoded;
  985. res->n_prompt_tokens = slot.task->n_tokens();
  986. res->post_sampling_probs = slot.task->params.post_sampling_probs;
  987. res->verbose = slot.task->params.verbose;
  988. res->res_type = slot.task->params.res_type;
  989. res->oaicompat_model = slot.task->params.oaicompat_model;
  990. res->oaicompat_cmpl_id = slot.task->params.oaicompat_cmpl_id;
  991. // populate res.probs_output
  992. if (slot.task->params.sampling.n_probs > 0) {
  993. res->prob_output = tkn; // copy the token probs
  994. }
  995. // populate timings if this is final response or timings_per_token is enabled
  996. if (slot.stop != STOP_TYPE_NONE || slot.task->params.timings_per_token) {
  997. res->timings = slot.get_timings();
  998. }
  999. queue_results.send(std::move(res));
  1000. }
  1001. void send_final_response(server_slot & slot) {
  1002. auto res = std::make_unique<server_task_result_cmpl_final>();
  1003. res->id = slot.task->id;
  1004. res->id_slot = slot.id;
  1005. res->index = slot.task->index;
  1006. res->content = slot.generated_text;
  1007. res->tokens = std::move(slot.generated_tokens);
  1008. res->timings = slot.get_timings();
  1009. res->prompt = slot.task->tokens.detokenize(ctx, true);
  1010. res->response_fields = std::move(slot.task->params.response_fields);
  1011. res->truncated = slot.truncated;
  1012. res->n_decoded = slot.n_decoded;
  1013. res->n_prompt_tokens = slot.task->n_tokens();
  1014. res->n_tokens_cached = slot.prompt.n_tokens();
  1015. res->has_new_line = slot.has_new_line;
  1016. res->stopping_word = slot.stopping_word;
  1017. res->stop = slot.stop;
  1018. res->post_sampling_probs = slot.task->params.post_sampling_probs;
  1019. res->verbose = slot.task->params.verbose;
  1020. res->stream = slot.task->params.stream;
  1021. res->include_usage = slot.task->params.include_usage;
  1022. res->res_type = slot.task->params.res_type;
  1023. res->oaicompat_model = slot.task->params.oaicompat_model;
  1024. res->oaicompat_cmpl_id = slot.task->params.oaicompat_cmpl_id;
  1025. res->oaicompat_msg = slot.update_chat_msg(res->oaicompat_msg_diffs);
  1026. // populate res.probs_output
  1027. if (slot.task->params.sampling.n_probs > 0) {
  1028. if (!slot.task->params.stream && slot.stop == STOP_TYPE_WORD) {
  1029. const llama_tokens stop_word_toks = common_tokenize(ctx, slot.stopping_word, false);
  1030. size_t safe_offset = std::min(slot.generated_token_probs.size(), stop_word_toks.size());
  1031. res->probs_output = std::vector<completion_token_output>(
  1032. slot.generated_token_probs.begin(),
  1033. slot.generated_token_probs.end() - safe_offset);
  1034. } else {
  1035. res->probs_output = std::vector<completion_token_output>(
  1036. slot.generated_token_probs.begin(),
  1037. slot.generated_token_probs.end());
  1038. }
  1039. }
  1040. res->generation_params = slot.task->params; // copy the parameters
  1041. queue_results.send(std::move(res));
  1042. }
  1043. void send_embedding(const server_slot & slot, const llama_batch & batch) {
  1044. auto res = std::make_unique<server_task_result_embd>();
  1045. res->id = slot.task->id;
  1046. res->index = slot.task->index;
  1047. res->n_tokens = slot.task->n_tokens();
  1048. res->res_type = slot.task->params.res_type;
  1049. const int n_embd = llama_model_n_embd(model);
  1050. std::vector<float> embd_res(n_embd, 0.0f);
  1051. for (int i = 0; i < batch.n_tokens; ++i) {
  1052. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  1053. continue;
  1054. }
  1055. const float * embd = nullptr;
  1056. if (llama_pooling_type(slot.ctx) == LLAMA_POOLING_TYPE_NONE) {
  1057. embd = llama_get_embeddings_ith(ctx, i);
  1058. } else {
  1059. embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1060. }
  1061. if (embd == nullptr) {
  1062. SLT_ERR(slot, "failed to get embeddings, token = %d, seq_id = %d\n", batch.token[i], batch.seq_id[i][0]);
  1063. res->embedding.push_back(std::vector<float>(n_embd, 0.0f));
  1064. continue;
  1065. }
  1066. // normalize only when there is pooling
  1067. if (llama_pooling_type(slot.ctx) != LLAMA_POOLING_TYPE_NONE) {
  1068. common_embd_normalize(embd, embd_res.data(), n_embd, slot.task->params.embd_normalize);
  1069. res->embedding.push_back(embd_res);
  1070. break;
  1071. }
  1072. res->embedding.emplace_back(embd, embd + n_embd);
  1073. }
  1074. SLT_DBG(slot, "%s", "sending embeddings\n");
  1075. queue_results.send(std::move(res));
  1076. }
  1077. void send_rerank(const server_slot & slot, const llama_batch & batch) {
  1078. auto res = std::make_unique<server_task_result_rerank>();
  1079. res->id = slot.task->id;
  1080. res->index = slot.task->index;
  1081. res->n_tokens = slot.task->n_tokens();
  1082. for (int i = 0; i < batch.n_tokens; ++i) {
  1083. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  1084. continue;
  1085. }
  1086. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1087. if (embd == NULL) {
  1088. embd = llama_get_embeddings_ith(ctx, i);
  1089. }
  1090. if (embd == NULL) {
  1091. SLT_ERR(slot, "failed to get embeddings, token = %d, seq_id = %d\n", batch.token[i], batch.seq_id[i][0]);
  1092. res->score = -1e6;
  1093. continue;
  1094. }
  1095. res->score = embd[0];
  1096. }
  1097. SLT_DBG(slot, "sending rerank result, res.score = %f\n", res->score);
  1098. queue_results.send(std::move(res));
  1099. }
  1100. //
  1101. // Functions to process the task
  1102. //
  1103. void process_single_task(server_task && task) {
  1104. switch (task.type) {
  1105. case SERVER_TASK_TYPE_COMPLETION:
  1106. case SERVER_TASK_TYPE_INFILL:
  1107. case SERVER_TASK_TYPE_EMBEDDING:
  1108. case SERVER_TASK_TYPE_RERANK:
  1109. {
  1110. const int id_slot = task.id_slot;
  1111. server_slot * slot = id_slot != -1 ? get_slot_by_id(id_slot) : get_available_slot(task);
  1112. if (slot == nullptr) {
  1113. // if no slot is available, we defer this task for processing later
  1114. SRV_DBG("no slot is available, defer task, id_task = %d\n", task.id);
  1115. queue_tasks.defer(std::move(task));
  1116. break;
  1117. }
  1118. if (slot->is_processing()) {
  1119. // if requested slot is unavailable, we defer this task for processing later
  1120. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1121. queue_tasks.defer(std::move(task));
  1122. break;
  1123. }
  1124. if (!launch_slot_with_task(*slot, std::move(task))) {
  1125. SRV_ERR("failed to launch slot with task, id_task = %d\n", task.id);
  1126. break;
  1127. }
  1128. } break;
  1129. case SERVER_TASK_TYPE_CANCEL:
  1130. {
  1131. // release slot linked with the task id
  1132. for (auto & slot : slots) {
  1133. if (slot.task && slot.task->id == task.id_target) {
  1134. slot.release();
  1135. break;
  1136. }
  1137. }
  1138. } break;
  1139. case SERVER_TASK_TYPE_NEXT_RESPONSE:
  1140. {
  1141. // do nothing
  1142. } break;
  1143. case SERVER_TASK_TYPE_METRICS:
  1144. {
  1145. json slots_data = json::array();
  1146. int n_idle_slots = 0;
  1147. int n_processing_slots = 0;
  1148. for (server_slot & slot : slots) {
  1149. json slot_data = slot.to_json(slots_debug == 0);
  1150. if (slot.is_processing()) {
  1151. n_processing_slots++;
  1152. } else {
  1153. n_idle_slots++;
  1154. }
  1155. slots_data.push_back(slot_data);
  1156. }
  1157. SRV_DBG("n_idle_slots = %d, n_processing_slots = %d\n", n_idle_slots, n_processing_slots);
  1158. auto res = std::make_unique<server_task_result_metrics>();
  1159. res->id = task.id;
  1160. res->slots_data = std::move(slots_data);
  1161. res->n_idle_slots = n_idle_slots;
  1162. res->n_processing_slots = n_processing_slots;
  1163. res->n_tasks_deferred = queue_tasks.queue_tasks_deferred_size();
  1164. res->t_start = metrics.t_start;
  1165. res->n_prompt_tokens_processed_total = metrics.n_prompt_tokens_processed_total;
  1166. res->t_prompt_processing_total = metrics.t_prompt_processing_total;
  1167. res->n_tokens_predicted_total = metrics.n_tokens_predicted_total;
  1168. res->t_tokens_generation_total = metrics.t_tokens_generation_total;
  1169. res->n_tokens_max = metrics.n_tokens_max;
  1170. res->n_prompt_tokens_processed = metrics.n_prompt_tokens_processed;
  1171. res->t_prompt_processing = metrics.t_prompt_processing;
  1172. res->n_tokens_predicted = metrics.n_tokens_predicted;
  1173. res->t_tokens_generation = metrics.t_tokens_generation;
  1174. res->n_decode_total = metrics.n_decode_total;
  1175. res->n_busy_slots_total = metrics.n_busy_slots_total;
  1176. if (task.metrics_reset_bucket) {
  1177. metrics.reset_bucket();
  1178. }
  1179. queue_results.send(std::move(res));
  1180. } break;
  1181. case SERVER_TASK_TYPE_SLOT_SAVE:
  1182. {
  1183. if (!check_no_mtmd(task.id)) {
  1184. break;
  1185. }
  1186. int id_slot = task.slot_action.slot_id;
  1187. server_slot * slot = get_slot_by_id(id_slot);
  1188. if (slot == nullptr) {
  1189. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1190. break;
  1191. }
  1192. if (slot->is_processing()) {
  1193. // if requested slot is unavailable, we defer this task for processing later
  1194. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1195. queue_tasks.defer(std::move(task));
  1196. break;
  1197. }
  1198. const size_t token_count = slot->prompt.tokens.size();
  1199. const int64_t t_start = ggml_time_us();
  1200. std::string filename = task.slot_action.filename;
  1201. std::string filepath = task.slot_action.filepath;
  1202. const llama_tokens & tokens = slot->prompt.tokens.get_text_tokens();
  1203. const size_t nwrite = llama_state_seq_save_file(ctx, filepath.c_str(), slot->id, tokens.data(), token_count);
  1204. const int64_t t_end = ggml_time_us();
  1205. const double t_save_ms = (t_end - t_start) / 1000.0;
  1206. auto res = std::make_unique<server_task_result_slot_save_load>();
  1207. res->id = task.id;
  1208. res->id_slot = id_slot;
  1209. res->filename = filename;
  1210. res->is_save = true;
  1211. res->n_tokens = token_count;
  1212. res->n_bytes = nwrite;
  1213. res->t_ms = t_save_ms;
  1214. queue_results.send(std::move(res));
  1215. } break;
  1216. case SERVER_TASK_TYPE_SLOT_RESTORE:
  1217. {
  1218. if (!check_no_mtmd(task.id)) break;
  1219. int id_slot = task.slot_action.slot_id;
  1220. server_slot * slot = get_slot_by_id(id_slot);
  1221. if (slot == nullptr) {
  1222. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1223. break;
  1224. }
  1225. if (slot->is_processing()) {
  1226. // if requested slot is unavailable, we defer this task for processing later
  1227. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1228. queue_tasks.defer(std::move(task));
  1229. break;
  1230. }
  1231. const int64_t t_start = ggml_time_us();
  1232. std::string filename = task.slot_action.filename;
  1233. std::string filepath = task.slot_action.filepath;
  1234. llama_tokens tokens;
  1235. tokens.resize(slot->n_ctx);
  1236. size_t token_count = 0;
  1237. size_t nread = llama_state_seq_load_file(ctx, filepath.c_str(), slot->id, tokens.data(), tokens.size(), &token_count);
  1238. if (nread == 0) {
  1239. slot->prompt.tokens.clear(); // KV may already been invalidated?
  1240. send_error(task, "Unable to restore slot, no available space in KV cache or invalid slot save file", ERROR_TYPE_INVALID_REQUEST);
  1241. break;
  1242. }
  1243. tokens.resize(token_count);
  1244. slot->prompt.tokens.clear();
  1245. slot->prompt.tokens.insert(tokens);
  1246. const int64_t t_end = ggml_time_us();
  1247. const double t_restore_ms = (t_end - t_start) / 1000.0;
  1248. auto res = std::make_unique<server_task_result_slot_save_load>();
  1249. res->id = task.id;
  1250. res->id_slot = id_slot;
  1251. res->filename = filename;
  1252. res->is_save = false;
  1253. res->n_tokens = token_count;
  1254. res->n_bytes = nread;
  1255. res->t_ms = t_restore_ms;
  1256. queue_results.send(std::move(res));
  1257. } break;
  1258. case SERVER_TASK_TYPE_SLOT_ERASE:
  1259. {
  1260. if (!check_no_mtmd(task.id)) {
  1261. break;
  1262. }
  1263. int id_slot = task.slot_action.slot_id;
  1264. server_slot * slot = get_slot_by_id(id_slot);
  1265. if (slot == nullptr) {
  1266. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1267. break;
  1268. }
  1269. if (slot->is_processing()) {
  1270. // if requested slot is unavailable, we defer this task for processing later
  1271. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1272. queue_tasks.defer(std::move(task));
  1273. break;
  1274. }
  1275. // Erase token cache
  1276. const size_t n_erased = slot->prompt.tokens.size();
  1277. clear_slot(*slot);
  1278. auto res = std::make_unique<server_task_result_slot_erase>();
  1279. res->id = task.id;
  1280. res->id_slot = id_slot;
  1281. res->n_erased = n_erased;
  1282. queue_results.send(std::move(res));
  1283. } break;
  1284. case SERVER_TASK_TYPE_SET_LORA:
  1285. {
  1286. params_base.lora_adapters = std::move(task.set_lora);
  1287. auto res = std::make_unique<server_task_result_apply_lora>();
  1288. res->id = task.id;
  1289. queue_results.send(std::move(res));
  1290. } break;
  1291. }
  1292. }
  1293. void update_slots() {
  1294. // check if all slots are idle
  1295. {
  1296. bool all_idle = true;
  1297. for (auto & slot : slots) {
  1298. if (slot.is_processing()) {
  1299. all_idle = false;
  1300. break;
  1301. }
  1302. }
  1303. if (all_idle) {
  1304. SRV_INF("%s", "all slots are idle\n");
  1305. return;
  1306. }
  1307. }
  1308. {
  1309. SRV_DBG("%s", "posting NEXT_RESPONSE\n");
  1310. server_task task(SERVER_TASK_TYPE_NEXT_RESPONSE);
  1311. task.id = queue_tasks.get_new_id();
  1312. queue_tasks.post(std::move(task));
  1313. }
  1314. // apply context-shift if needed
  1315. // TODO: simplify and improve
  1316. for (server_slot & slot : slots) {
  1317. if (slot.state == SLOT_STATE_GENERATING && slot.prompt.n_tokens() + 1 >= slot.n_ctx) {
  1318. if (!params_base.ctx_shift) {
  1319. // this check is redundant (for good)
  1320. // we should never get here, because generation should already stopped in process_token()
  1321. send_error(slot, "context shift is disabled", ERROR_TYPE_SERVER);
  1322. slot.release();
  1323. continue;
  1324. }
  1325. if (mctx) {
  1326. // we should never reach this because params_base.ctx_shift is automatically disabled if mmproj is loaded
  1327. // we don't support ctx_shift because an image chunk may contains multiple tokens
  1328. GGML_ABORT("not supported by multimodal");
  1329. }
  1330. // Shift context
  1331. int n_keep = slot.task->params.n_keep < 0 ? slot.task->n_tokens() : slot.task->params.n_keep;
  1332. if (add_bos_token) {
  1333. n_keep += 1;
  1334. }
  1335. n_keep = std::min(slot.n_ctx - 4, n_keep);
  1336. const int n_left = slot.prompt.n_tokens() - n_keep;
  1337. const int n_discard = slot.task->params.n_discard ? slot.task->params.n_discard : (n_left / 2);
  1338. SLT_WRN(slot, "slot context shift, n_keep = %d, n_left = %d, n_discard = %d\n", n_keep, n_left, n_discard);
  1339. llama_memory_seq_rm (llama_get_memory(ctx), slot.id, n_keep , n_keep + n_discard);
  1340. llama_memory_seq_add(llama_get_memory(ctx), slot.id, n_keep + n_discard, slot.prompt.n_tokens(), -n_discard);
  1341. // add generated tokens to cache
  1342. // ref: https://github.com/ggml-org/llama.cpp/pull/16818#discussion_r2473269481
  1343. {
  1344. GGML_ASSERT(!slot.prompt.tokens.has_mtmd);
  1345. llama_tokens new_tokens = slot.prompt.tokens.get_text_tokens(); // copy
  1346. for (size_t i = n_keep + n_discard; i < new_tokens.size(); i++) {
  1347. new_tokens[i - n_discard] = new_tokens[i];
  1348. }
  1349. new_tokens.resize(slot.prompt.tokens.size() - n_discard);
  1350. slot.prompt.tokens.clear();
  1351. slot.prompt.tokens.insert(new_tokens);
  1352. }
  1353. slot.truncated = true;
  1354. }
  1355. }
  1356. // start populating the batch for this iteration
  1357. common_batch_clear(batch);
  1358. // track if given slot can be batched with slots already in the batch
  1359. server_slot * slot_batched = nullptr;
  1360. auto accept_special_token = [&](server_slot & slot, llama_token token) {
  1361. return params_base.special ||
  1362. slot.task->params.sampling.preserved_tokens.find(token) != slot.task->params.sampling.preserved_tokens.end();
  1363. };
  1364. // first, add sampled tokens from any ongoing sequences
  1365. for (auto & slot : slots) {
  1366. if (slot.state != SLOT_STATE_GENERATING) {
  1367. continue;
  1368. }
  1369. // check if we can batch this slot with the previous one
  1370. if (!slot_batched) {
  1371. slot_batched = &slot;
  1372. } else if (!slot_batched->can_batch_with(slot)) {
  1373. continue;
  1374. }
  1375. slot.i_batch = batch.n_tokens;
  1376. common_batch_add(batch, slot.sampled, slot.prompt.tokens.pos_next(), { slot.id }, true);
  1377. slot.prompt.tokens.push_back(slot.sampled);
  1378. SLT_DBG(slot, "slot decode token, n_ctx = %d, n_tokens = %d, truncated = %d\n",
  1379. slot.n_ctx, slot.prompt.n_tokens(), slot.truncated);
  1380. }
  1381. // process in chunks of params.n_batch
  1382. int32_t n_batch = llama_n_batch(ctx);
  1383. int32_t n_ubatch = llama_n_ubatch(ctx);
  1384. float alora_scale = -1.0f;
  1385. size_t alora_disabled_id = 0;
  1386. // next, batch any pending prompts without exceeding n_batch
  1387. if (params_base.cont_batching || batch.n_tokens == 0) {
  1388. for (auto & slot : slots) {
  1389. if (!slot.is_processing()) {
  1390. continue;
  1391. }
  1392. // check if we can batch this slot with the previous one
  1393. if (slot_batched && !slot_batched->can_batch_with(slot)) {
  1394. continue;
  1395. }
  1396. // this slot still has a prompt to be processed
  1397. if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_STARTED) {
  1398. const auto & input_tokens = slot.task->tokens;
  1399. // TODO: maybe move branch to outside of this loop in the future
  1400. if (slot.state == SLOT_STATE_STARTED) {
  1401. slot.t_start_process_prompt = ggml_time_us();
  1402. slot.t_start_generation = 0;
  1403. slot.state = SLOT_STATE_PROCESSING_PROMPT;
  1404. SLT_INF(slot, "new prompt, n_ctx_slot = %d, n_keep = %d, task.n_tokens = %d\n",
  1405. slot.n_ctx, slot.task->params.n_keep, slot.task->n_tokens());
  1406. // print prompt tokens (for debugging)
  1407. /*if (1) {
  1408. // first 16 tokens (avoid flooding logs)
  1409. for (int i = 0; i < std::min<int>(16, input_tokens.size()); i++) {
  1410. SLT_DBG(slot, "prompt token %3d: %6d '%s'\n", i, input_tokens[i], common_token_to_piece(ctx, input_tokens[i]).c_str());
  1411. }
  1412. } else {
  1413. // all
  1414. for (int i = 0; i < (int) input_tokens.size(); i++) {
  1415. SLT_DBG(slot, "prompt token %3d: %6d '%s'\n", i, input_tokens[i], common_token_to_piece(ctx, input_tokens[i]).c_str());
  1416. }
  1417. }*/
  1418. // keep track how many tokens we can reuse from the previous state
  1419. int n_past = 0;
  1420. // empty prompt passed -> release the slot and send empty response
  1421. if (input_tokens.empty()) {
  1422. SLT_WRN(slot, "%s", "empty prompt - releasing slot\n");
  1423. slot.print_timings();
  1424. send_final_response(slot);
  1425. slot.release();
  1426. continue;
  1427. }
  1428. // TODO: support memory-less logits computation
  1429. if (slot.need_logits() && !llama_get_memory(ctx)) {
  1430. send_error(slot, "the current context does not logits computation. skipping", ERROR_TYPE_SERVER);
  1431. slot.release();
  1432. continue;
  1433. }
  1434. if (!slot.can_split()) {
  1435. if (slot.task->n_tokens() > n_ubatch) {
  1436. send_error(slot, "input is too large to process. increase the physical batch size", ERROR_TYPE_SERVER);
  1437. slot.release();
  1438. continue;
  1439. }
  1440. if (slot.task->n_tokens() > slot.n_ctx) {
  1441. send_error(slot, "input is larger than the max context size. skipping", ERROR_TYPE_EXCEED_CONTEXT_SIZE);
  1442. slot.release();
  1443. continue;
  1444. }
  1445. } else {
  1446. if (slot.task->n_tokens() >= slot.n_ctx) {
  1447. send_error(slot, "the request exceeds the available context size, try increasing it", ERROR_TYPE_EXCEED_CONTEXT_SIZE);
  1448. slot.release();
  1449. continue;
  1450. }
  1451. if (slot.task->params.cache_prompt) {
  1452. // reuse any previously computed tokens that are common with the new prompt
  1453. n_past = slot.prompt.tokens.get_common_prefix(input_tokens);
  1454. // if there is an alora invoked, don't cache after the invocation start
  1455. if (slot.alora_invocation_start > 0) {
  1456. SLT_DBG(slot, "only caching to alora invocation start (n_past = %d, alora_invocation_start = %d)\n", n_past, slot.alora_invocation_start);
  1457. n_past = std::min(n_past, slot.alora_invocation_start - 1);
  1458. }
  1459. // reuse chunks from the cached prompt by shifting their KV cache in the new position
  1460. if (params_base.n_cache_reuse > 0) {
  1461. GGML_ASSERT(!slot.prompt.tokens.has_mtmd);
  1462. size_t head_c = n_past; // cache
  1463. size_t head_p = n_past; // current prompt
  1464. if (mctx) {
  1465. // we should never reach this
  1466. GGML_ABORT("not supported by multimodal");
  1467. }
  1468. SLT_DBG(slot, "trying to reuse chunks with size > %d, n_past = %d\n", params_base.n_cache_reuse, n_past);
  1469. while (head_c < slot.prompt.tokens.size() &&
  1470. head_p < input_tokens.size()) {
  1471. size_t n_match = 0;
  1472. while (head_c + n_match < slot.prompt.tokens.size() &&
  1473. head_p + n_match < input_tokens.size() &&
  1474. slot.prompt.tokens[head_c + n_match] == input_tokens[head_p + n_match]) {
  1475. n_match++;
  1476. }
  1477. if (n_match >= (size_t) params_base.n_cache_reuse) {
  1478. SLT_INF(slot, "reusing chunk with size %zu, shifting KV cache [%zu, %zu) -> [%zu, %zu)\n", n_match, head_c, head_c + n_match, head_p, head_p + n_match);
  1479. //for (size_t i = head_p; i < head_p + n_match; i++) {
  1480. // SLT_DBG(slot, "cache token %3zu: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  1481. //}
  1482. const int64_t kv_shift = (int64_t) head_p - (int64_t) head_c;
  1483. llama_memory_seq_rm (llama_get_memory(ctx), slot.id, head_p, head_c);
  1484. llama_memory_seq_add(llama_get_memory(ctx), slot.id, head_c, head_c + n_match, kv_shift);
  1485. for (size_t i = 0; i < n_match; i++) {
  1486. slot.prompt.tokens.set_token(head_p + i, slot.prompt.tokens[head_c + i]);
  1487. n_past++;
  1488. }
  1489. head_c += n_match;
  1490. head_p += n_match;
  1491. } else {
  1492. head_c += 1;
  1493. }
  1494. }
  1495. SLT_DBG(slot, "after context reuse, new n_past = %d\n", n_past);
  1496. }
  1497. } else {
  1498. // if we don't cache the prompt, we have to remove all previous tokens
  1499. n_past = 0;
  1500. }
  1501. // note: when n_swa == 0, the model does not use SWA, which is equivalent to a window of 1
  1502. const auto n_swa = std::max(1, llama_model_n_swa(model));
  1503. // the largest pos_min required for a checkpoint to be useful
  1504. const auto pos_min_thold = std::max(0, n_past - n_swa);
  1505. // note: disallow with mtmd contexts for now
  1506. // https://github.com/ggml-org/llama.cpp/issues/17043
  1507. if (!mctx && n_past > 0 && n_past < slot.prompt.n_tokens()) {
  1508. const auto pos_min = llama_memory_seq_pos_min(llama_get_memory(ctx), slot.id);
  1509. if (pos_min == -1) {
  1510. SLT_ERR(slot, "n_past = %d, slot.prompt.tokens.size() = %d, seq_id = %d, pos_min = %d\n", n_past, (int) slot.prompt.tokens.size(), slot.id, pos_min);
  1511. GGML_ABORT("pos_min == -1, but n_past > 0 - should not happen: https://github.com/ggml-org/llama.cpp/pull/13833#discussion_r2116181237");
  1512. }
  1513. // when the prompt prefix does not match, print the tokens around the mismatch
  1514. // this is useful for debugging prompt caching
  1515. if (slots_debug) {
  1516. const int np0 = std::max<int>(n_past - 4, 0);
  1517. const int np1 = std::min<int>(n_past + 6, std::min(slot.prompt.tokens.size(), slot.task->tokens.size()));
  1518. std::stringstream ss0;
  1519. std::stringstream ss1;
  1520. std::stringstream st0;
  1521. std::stringstream st1;
  1522. ss0 << "old: ... ";
  1523. ss1 << "new: ... ";
  1524. for (int i = np0; i < np1; i++) {
  1525. if (i == n_past) {
  1526. ss0 << " | ";
  1527. ss1 << " | ";
  1528. }
  1529. {
  1530. const auto token = slot.prompt.tokens[i];
  1531. const auto piece = token != LLAMA_TOKEN_NULL ? common_token_to_piece(ctx, token) : "[mtmd]";
  1532. ss0 << piece;
  1533. st0 << std::setw(8) << token;
  1534. }
  1535. {
  1536. const auto token = slot.task->tokens[i];
  1537. const auto piece = token != LLAMA_TOKEN_NULL ? common_token_to_piece(ctx, token) : "[mtmd]";
  1538. ss1 << piece;
  1539. st1 << std::setw(8) << token;
  1540. }
  1541. }
  1542. SLT_WRN(slot, "%s\n", ss0.str().c_str());
  1543. SLT_WRN(slot, "%s\n", ss1.str().c_str());
  1544. SLT_WRN(slot, "%s\n", st0.str().c_str());
  1545. SLT_WRN(slot, "%s\n", st1.str().c_str());
  1546. }
  1547. if (pos_min > pos_min_thold) {
  1548. // TODO: support can be added in the future when corresponding vision models get released
  1549. GGML_ASSERT(!slot.prompt.tokens.has_mtmd);
  1550. SLT_WRN(slot, "n_past = %d, slot.prompt.tokens.size() = %d, seq_id = %d, pos_min = %d, n_swa = %d\n", n_past, (int) slot.prompt.tokens.size(), slot.id, pos_min, n_swa);
  1551. // search for a context checkpoint
  1552. const auto it = std::find_if(
  1553. slot.prompt.checkpoints.rbegin(),
  1554. slot.prompt.checkpoints.rend(),
  1555. [&](const auto & cur) {
  1556. // guarantee that a checkpoint will result in at least one token being processed [TAG_PROMPT_LOGITS]
  1557. return cur.pos_min < pos_min_thold;
  1558. }
  1559. );
  1560. bool do_reset = it == slot.prompt.checkpoints.rend();
  1561. if (!do_reset) {
  1562. // restore the context checkpoint
  1563. const size_t checkpoint_size = it->data.size();
  1564. const size_t n = llama_state_seq_set_data_ext(ctx, it->data.data(), checkpoint_size, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY);
  1565. if (n != checkpoint_size) {
  1566. SLT_ERR(slot, "failed to restore context checkpoint (pos_min = %d, pos_max = %d, size = %.3f MiB)\n", it->pos_min, it->pos_max, (float) checkpoint_size / 1024 / 1024);
  1567. do_reset = true;
  1568. //printf("[DEBUG] `do_reset` was set to `true` after failing to restore a checkpoint");
  1569. } else {
  1570. n_past = std::min(n_past, std::max(it->pos_min + 1, it->pos_max));
  1571. SLT_WRN(slot, "restored context checkpoint (pos_min = %d, pos_max = %d, size = %.3f MiB)\n", it->pos_min, it->pos_max, (float) checkpoint_size / 1024 / 1024);
  1572. }
  1573. }
  1574. if (do_reset) {
  1575. SLT_WRN(slot, "forcing full prompt re-processing due to lack of cache data (likely due to SWA or hybrid/recurrent memory, see %s)\n",
  1576. "https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055");
  1577. n_past = 0;
  1578. }
  1579. }
  1580. }
  1581. {
  1582. // erase any checkpoints with pos_min > pos_min_thold
  1583. for (auto it = slot.prompt.checkpoints.begin(); it != slot.prompt.checkpoints.end();) {
  1584. const auto & cur = *it;
  1585. if (cur.pos_min > pos_min_thold) {
  1586. SLT_WRN(slot, "erased invalidated context checkpoint (pos_min = %d, pos_max = %d, n_swa = %d, size = %.3f MiB)\n", cur.pos_min, cur.pos_max, n_swa, (float) cur.data.size() / 1024 / 1024);
  1587. it = slot.prompt.checkpoints.erase(it);
  1588. } else {
  1589. ++it;
  1590. }
  1591. }
  1592. }
  1593. }
  1594. // [TAG_PROMPT_LOGITS]
  1595. if (n_past == slot.task->n_tokens() && n_past > 0) {
  1596. SLT_WRN(slot, "need to evaluate at least 1 token for each active slot (n_past = %d, task.n_tokens() = %d)\n", n_past, slot.task->n_tokens());
  1597. n_past--;
  1598. SLT_WRN(slot, "n_past was set to %d\n", n_past);
  1599. }
  1600. slot.n_prompt_tokens_cache = n_past;
  1601. slot.n_prompt_tokens_processed = 0;
  1602. slot.prompt.tokens.keep_first(n_past);
  1603. }
  1604. if (!slot.can_split()) {
  1605. // cannot fit the prompt in the current batch - will try next iter
  1606. if (batch.n_tokens + slot.task->n_tokens() > n_batch) {
  1607. continue;
  1608. }
  1609. }
  1610. // truncate any tokens that are beyond n_past for this slot
  1611. const llama_pos p0 = slot.prompt.tokens.pos_next();
  1612. SLT_INF(slot, "n_tokens = %d, memory_seq_rm [%d, end)\n", slot.prompt.n_tokens(), p0);
  1613. if (!llama_memory_seq_rm(llama_get_memory(ctx), slot.id, p0, -1)) {
  1614. SLT_WRN(slot, "failed to truncate tokens with position >= %d - clearing the memory\n", p0);
  1615. clear_slot(slot);
  1616. // there is no common part left
  1617. slot.n_prompt_tokens_cache = 0;
  1618. }
  1619. // check if we should process the image
  1620. if (slot.prompt.n_tokens() < slot.task->n_tokens() && input_tokens[slot.prompt.n_tokens()] == LLAMA_TOKEN_NULL) {
  1621. // process the image
  1622. size_t n_tokens_out = 0;
  1623. int32_t res = input_tokens.process_chunk(ctx, mctx, slot.prompt.n_tokens(), slot.prompt.tokens.pos_next(), slot.id, n_tokens_out);
  1624. if (res != 0) {
  1625. SLT_ERR(slot, "failed to process image, res = %d\n", res);
  1626. send_error(slot, "failed to process image", ERROR_TYPE_SERVER);
  1627. slot.release();
  1628. continue;
  1629. }
  1630. slot.n_prompt_tokens_processed += n_tokens_out;
  1631. // add the image chunk to cache
  1632. {
  1633. const auto & chunk = input_tokens.find_chunk(slot.prompt.n_tokens());
  1634. slot.prompt.tokens.push_back(chunk.get()); // copy
  1635. }
  1636. }
  1637. // If using an alora, there may be uncached tokens that come
  1638. // before the invocation sequence. When this happens, the
  1639. // tokens before the invocation sequence need to be
  1640. // processed without the adapter in a separate batch, then
  1641. // the adapter needs to be enabled for the remaining tokens.
  1642. if (lora_all_alora(slot.lora) && slot.alora_invocation_start - 1 > slot.prompt.n_tokens()) {
  1643. SLT_DBG(slot, "processing pre-alora tokens without the adapter (n_tokens = %d, alora_invocation_start = %d)\n", slot.prompt.n_tokens(), slot.alora_invocation_start);
  1644. const auto & enabled_loras = lora_get_enabled_ids(slot.lora);
  1645. GGML_ASSERT(enabled_loras.size() == 1);
  1646. alora_scale = slot.lora[enabled_loras[0]].scale;
  1647. slot.lora[enabled_loras[0]].scale = 0.0f;
  1648. alora_disabled_id = enabled_loras[0];
  1649. }
  1650. bool do_checkpoint = params_base.n_ctx_checkpoints > 0;
  1651. // make checkpoints only for completion tasks
  1652. do_checkpoint = do_checkpoint && slot.task->type == SERVER_TASK_TYPE_COMPLETION;
  1653. // make a checkpoint of the parts of the memory that cannot be rolled back.
  1654. // checkpoints are created only if:
  1655. // - the model uses SWA and we are not using `swa_full`
  1656. // - the model architecture is marked as recurrent or hybrid
  1657. //
  1658. // TODO: try to make this conditional on the context or the memory module, instead of the model type
  1659. do_checkpoint = do_checkpoint && (
  1660. llama_model_is_recurrent(model) ||
  1661. llama_model_is_hybrid(model) ||
  1662. (llama_model_n_swa(model) > 0 && !params_base.swa_full)
  1663. );
  1664. // add prompt tokens for processing in the current batch
  1665. while (slot.prompt.n_tokens() < slot.task->n_tokens() && batch.n_tokens < n_batch) {
  1666. // get next token to process
  1667. llama_token cur_tok = input_tokens[slot.prompt.n_tokens()];
  1668. if (cur_tok == LLAMA_TOKEN_NULL) {
  1669. break; // end of text chunk
  1670. }
  1671. // if this is an alora request with pre-invocation
  1672. // tokens that are not cached, we need to stop filling
  1673. // this batch at those pre-invocation tokens.
  1674. if (alora_scale > 0 && slot.prompt.n_tokens() == slot.alora_invocation_start - 1) {
  1675. SLT_DBG(slot, "stop prompt batch filling at (n_tokens = %d, alora_invocation_start = %d)\n", slot.prompt.n_tokens(), slot.alora_invocation_start);
  1676. break;
  1677. }
  1678. // embedding requires all tokens in the batch to be output
  1679. common_batch_add(batch,
  1680. cur_tok,
  1681. slot.prompt.tokens.pos_next(),
  1682. { slot.id },
  1683. slot.need_embd());
  1684. slot.prompt.tokens.push_back(cur_tok);
  1685. slot.n_prompt_tokens_processed++;
  1686. // process the last few tokens of the prompt separately in order to allow for a checkpoint to be created.
  1687. if (do_checkpoint && slot.task->n_tokens() - slot.prompt.n_tokens() == 64) {
  1688. break;
  1689. }
  1690. }
  1691. // SLT_INF(slot, "new slot.prompt.tokens: %s\n", slot.slot.prompt.tokens.str().c_str());
  1692. SLT_INF(slot, "prompt processing progress, n_tokens = %d, batch.n_tokens = %d, progress = %f\n", slot.prompt.n_tokens(), batch.n_tokens, (float) slot.prompt.n_tokens() / slot.task->n_tokens());
  1693. // entire prompt has been processed
  1694. if (slot.prompt.n_tokens() == slot.task->n_tokens()) {
  1695. slot.state = SLOT_STATE_DONE_PROMPT;
  1696. GGML_ASSERT(batch.n_tokens > 0);
  1697. common_sampler_reset(slot.smpl);
  1698. // Process all prompt tokens through sampler system
  1699. for (int i = 0; i < slot.task->n_tokens(); ++i) {
  1700. llama_token id = input_tokens[i];
  1701. if (id != LLAMA_TOKEN_NULL) {
  1702. common_sampler_accept(slot.smpl, id, false);
  1703. }
  1704. }
  1705. // extract the logits only for the last token
  1706. batch.logits[batch.n_tokens - 1] = true;
  1707. slot.n_decoded = 0;
  1708. slot.i_batch = batch.n_tokens - 1;
  1709. SLT_INF(slot, "prompt done, n_tokens = %d, batch.n_tokens = %d\n", slot.prompt.n_tokens(), batch.n_tokens);
  1710. const auto pos_min = llama_memory_seq_pos_min(llama_get_memory(ctx), slot.id);
  1711. const auto pos_max = llama_memory_seq_pos_max(llama_get_memory(ctx), slot.id);
  1712. // no need for empty or small checkpoints
  1713. do_checkpoint = do_checkpoint && (pos_min >= 0 && pos_max >= 64);
  1714. // no need to create checkpoints that are too close together
  1715. do_checkpoint = do_checkpoint && (slot.prompt.checkpoints.empty() || pos_max > slot.prompt.checkpoints.back().pos_max + 64);
  1716. if (do_checkpoint) {
  1717. while (slot.prompt.checkpoints.size() >= (size_t) params_base.n_ctx_checkpoints) {
  1718. // make room for the new checkpoint, if needed
  1719. const auto & cur = slot.prompt.checkpoints.front();
  1720. SLT_WRN(slot, "erasing old context checkpoint (pos_min = %d, pos_max = %d, size = %.3f MiB)\n",
  1721. cur.pos_min, cur.pos_max, (float) cur.data.size() / 1024 / 1024);
  1722. slot.prompt.checkpoints.erase(slot.prompt.checkpoints.begin());
  1723. }
  1724. const size_t checkpoint_size = llama_state_seq_get_size_ext(ctx, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY);
  1725. auto & cur = slot.prompt.checkpoints.emplace_back(server_prompt_checkpoint{
  1726. /*.pos_min = */ pos_min,
  1727. /*.pos_max = */ pos_max,
  1728. /*.data = */ std::vector<uint8_t>(checkpoint_size),
  1729. });
  1730. llama_state_seq_get_data_ext(ctx, cur.data.data(), checkpoint_size, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY);
  1731. SLT_WRN(slot, "created context checkpoint %d of %d (pos_min = %d, pos_max = %d, size = %.3f MiB)\n",
  1732. (int) slot.prompt.checkpoints.size(), params_base.n_ctx_checkpoints, cur.pos_min, cur.pos_max, (float) cur.data.size() / 1024 / 1024);
  1733. }
  1734. }
  1735. }
  1736. if (!slot_batched) {
  1737. slot_batched = &slot;
  1738. }
  1739. if (batch.n_tokens >= n_batch) {
  1740. break;
  1741. }
  1742. }
  1743. }
  1744. if (batch.n_tokens == 0) {
  1745. SRV_WRN("%s", "no tokens to decode\n");
  1746. return;
  1747. }
  1748. SRV_DBG("decoding batch, n_tokens = %d\n", batch.n_tokens);
  1749. if (slot_batched) {
  1750. // apply lora, only need to do it once per batch
  1751. common_set_adapter_lora(ctx, slot_batched->lora);
  1752. // if the lora is temporarily disabled for an alora, re-enable it
  1753. // for next time
  1754. if (alora_scale > 0.0f) {
  1755. SRV_DBG("re-enabling alora with scale %f\n", alora_scale);
  1756. slot_batched->lora[alora_disabled_id].scale = alora_scale;
  1757. }
  1758. llama_set_embeddings(ctx, slot_batched->need_embd());
  1759. }
  1760. int32_t i_next = 0;
  1761. // process the created batch of tokens
  1762. for (int32_t i = 0; i < batch.n_tokens; i = i_next) {
  1763. const int32_t n_tokens = std::min(n_batch, batch.n_tokens - i);
  1764. llama_batch batch_view = {
  1765. n_tokens,
  1766. batch.token + i,
  1767. nullptr,
  1768. batch.pos + i,
  1769. batch.n_seq_id + i,
  1770. batch.seq_id + i,
  1771. batch.logits + i,
  1772. };
  1773. const int ret = llama_decode(ctx, batch_view);
  1774. metrics.on_decoded(slots);
  1775. if (ret != 0) {
  1776. {
  1777. std::string err;
  1778. if (n_batch == 1 && ret == 1) {
  1779. // TODO: try to terminate only the largest active slot/sequence and continue with the rest
  1780. // need to remove the tokens from the current batch too
  1781. err = "Context size has been exceeded.";
  1782. }
  1783. if (ret == -1) {
  1784. err = "Invalid input batch.";
  1785. }
  1786. if (ret < -1) {
  1787. // TODO: update slot state based on llama_memory_seq_pos_min() and llama_memory_seq_pos_max()
  1788. err = "Compute error.";
  1789. }
  1790. // TODO: handle ret == 2 (abort) when we start aborting
  1791. if (!err.empty()) {
  1792. SRV_ERR("%s i = %d, n_batch = %d, ret = %d\n", err.c_str(), i, n_batch, ret);
  1793. for (auto & slot : slots) {
  1794. if (slot.is_processing()) {
  1795. send_error(slot, err);
  1796. slot.release();
  1797. // note: it's complicated to keep track of how much of the current batch has been
  1798. // processed before the error occurred, so we simply clear the entire context
  1799. clear_slot(slot);
  1800. }
  1801. }
  1802. break;
  1803. }
  1804. }
  1805. // retry with half the batch size to try to find a free slot in the KV cache
  1806. if (!try_clear_idle_slots()) {
  1807. n_batch /= 2;
  1808. }
  1809. SRV_WRN("failed to find free space in the KV cache, retrying with smaller batch size, i = %d, n_batch = %d, ret = %d\n", i, n_batch, ret);
  1810. continue; // continue loop of n_batch
  1811. }
  1812. // move the head of the batch forward with the number of tokens we just processed
  1813. i_next = i + n_tokens;
  1814. // on successful decode, restore the original batch size
  1815. n_batch = llama_n_batch(ctx);
  1816. for (auto & slot : slots) {
  1817. // optionally send prompt processing progress
  1818. if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_DONE_PROMPT) {
  1819. if (slot.task->params.stream && slot.task->params.return_progress) {
  1820. send_partial_response(slot, {}, true);
  1821. }
  1822. }
  1823. if (slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens)) {
  1824. continue; // continue loop of slots
  1825. }
  1826. if (slot.state == SLOT_STATE_DONE_PROMPT) {
  1827. if (slot.task->type == SERVER_TASK_TYPE_EMBEDDING) {
  1828. // prompt evaluated for embedding
  1829. send_embedding(slot, batch_view);
  1830. slot.release();
  1831. slot.i_batch = -1;
  1832. continue; // continue loop of slots
  1833. }
  1834. if (slot.task->type == SERVER_TASK_TYPE_RERANK) {
  1835. send_rerank(slot, batch_view);
  1836. slot.release();
  1837. slot.i_batch = -1;
  1838. continue; // continue loop of slots
  1839. }
  1840. // prompt evaluated for next-token prediction
  1841. slot.state = SLOT_STATE_GENERATING;
  1842. } else if (slot.state != SLOT_STATE_GENERATING) {
  1843. continue; // continue loop of slots
  1844. }
  1845. const int tok_idx = slot.i_batch - i;
  1846. llama_token id = common_sampler_sample(slot.smpl, ctx, tok_idx);
  1847. slot.i_batch = -1;
  1848. common_sampler_accept(slot.smpl, id, true);
  1849. slot.n_decoded += 1;
  1850. const int64_t t_current = ggml_time_us();
  1851. if (slot.n_decoded == 1) {
  1852. slot.t_start_generation = t_current;
  1853. slot.t_prompt_processing = (slot.t_start_generation - slot.t_start_process_prompt) / 1e3;
  1854. metrics.on_prompt_eval(slot);
  1855. }
  1856. slot.t_token_generation = std::max<int64_t>(1, t_current - slot.t_start_generation) / 1e3;
  1857. completion_token_output result;
  1858. result.tok = id;
  1859. result.text_to_send = common_token_to_piece(ctx, result.tok, accept_special_token(slot, result.tok));
  1860. result.prob = 1.0f; // TODO: set it here instead of doing inside populate_token_probs
  1861. if (slot.task->params.sampling.n_probs > 0) {
  1862. populate_token_probs(slot, result, slot.task->params.post_sampling_probs, params_base.special, tok_idx);
  1863. }
  1864. if (!process_token(result, slot)) {
  1865. // release slot because of stop condition
  1866. slot.print_timings();
  1867. send_final_response(slot);
  1868. metrics.on_prediction(slot);
  1869. slot.release();
  1870. continue;
  1871. }
  1872. }
  1873. // do speculative decoding
  1874. // TODO: rework to have a single draft llama_context shared across all slots [TAG_SERVER_SPEC_REWORK]
  1875. // perform the speculative drafting for all sequences at the same time in a single batch
  1876. for (auto & slot : slots) {
  1877. if (!slot.is_processing() || !slot.can_speculate()) {
  1878. continue;
  1879. }
  1880. if (slot.state != SLOT_STATE_GENERATING) {
  1881. continue;
  1882. }
  1883. if (mctx) {
  1884. // we should never reach this, as speculative is automatically disabled if mmproj is loaded
  1885. GGML_ABORT("not supported by multimodal");
  1886. }
  1887. // determine the max draft that fits the current slot state
  1888. int n_draft_max = slot.task->params.speculative.n_max;
  1889. // note: slot.prompt is not yet expanded with the `id` token sampled above
  1890. // also, need to leave space for 1 extra token to allow context shifts
  1891. n_draft_max = std::min(n_draft_max, slot.n_ctx - slot.prompt.n_tokens() - 2);
  1892. if (slot.n_remaining > 0) {
  1893. n_draft_max = std::min(n_draft_max, slot.n_remaining - 1);
  1894. }
  1895. SLT_DBG(slot, "max possible draft: %d\n", n_draft_max);
  1896. if (n_draft_max < slot.task->params.speculative.n_min) {
  1897. SLT_DBG(slot, "the max possible draft is too small: %d < %d - skipping speculative decoding\n", n_draft_max, slot.task->params.speculative.n_min);
  1898. continue;
  1899. }
  1900. llama_token id = slot.sampled;
  1901. struct common_speculative_params params_spec;
  1902. params_spec.n_draft = n_draft_max;
  1903. params_spec.n_reuse = llama_n_ctx(slot.ctx_dft) - slot.task->params.speculative.n_max;
  1904. params_spec.p_min = slot.task->params.speculative.p_min;
  1905. const llama_tokens & cached_text_tokens = slot.prompt.tokens.get_text_tokens();
  1906. llama_tokens draft = common_speculative_gen_draft(slot.spec, params_spec, cached_text_tokens, id);
  1907. // ignore small drafts
  1908. if (slot.task->params.speculative.n_min > (int) draft.size()) {
  1909. SLT_DBG(slot, "ignoring small draft: %d < %d\n", (int) draft.size(), slot.task->params.speculative.n_min);
  1910. continue;
  1911. }
  1912. // keep track of total number of drafted tokens tested
  1913. slot.n_draft_total += draft.size();
  1914. // construct the speculation batch
  1915. common_batch_clear(slot.batch_spec);
  1916. common_batch_add (slot.batch_spec, id, slot.prompt.tokens.pos_next(), { slot.id }, true);
  1917. for (size_t i = 0; i < draft.size(); ++i) {
  1918. common_batch_add(slot.batch_spec, draft[i], slot.prompt.tokens.pos_next() + 1 + i, { slot.id }, true);
  1919. }
  1920. SLT_DBG(slot, "decoding speculative batch, size = %d\n", slot.batch_spec.n_tokens);
  1921. llama_decode(ctx, slot.batch_spec);
  1922. // the accepted tokens from the speculation
  1923. const auto ids = common_sampler_sample_and_accept_n(slot.smpl, ctx, draft);
  1924. slot.n_decoded += ids.size();
  1925. // update how many tokens out of those tested were accepted
  1926. slot.n_draft_accepted += ids.size() - 1;
  1927. slot.prompt.tokens.push_back(id);
  1928. slot.prompt.tokens.insert({ids.begin(), ids.end() - 1});
  1929. llama_memory_seq_rm(llama_get_memory(ctx), slot.id, slot.prompt.n_tokens(), -1);
  1930. for (size_t i = 0; i < ids.size(); ++i) {
  1931. completion_token_output result;
  1932. result.tok = ids[i];
  1933. result.text_to_send = common_token_to_piece(ctx, result.tok, accept_special_token(slot, result.tok));
  1934. result.prob = 1.0f; // set later
  1935. // TODO: set result.probs
  1936. if (!process_token(result, slot)) {
  1937. slot.print_timings();
  1938. send_final_response(slot);
  1939. metrics.on_prediction(slot);
  1940. slot.release();
  1941. break;
  1942. }
  1943. }
  1944. SLT_DBG(slot, "accepted %d/%d draft tokens, new n_tokens = %d\n", (int) ids.size() - 1, (int) draft.size(), slot.prompt.n_tokens());
  1945. }
  1946. }
  1947. SRV_DBG("%s", "run slots completed\n");
  1948. }
  1949. json model_meta() const {
  1950. return json {
  1951. {"vocab_type", llama_vocab_type (vocab)},
  1952. {"n_vocab", llama_vocab_n_tokens (vocab)},
  1953. {"n_ctx_train", llama_model_n_ctx_train(model)},
  1954. {"n_embd", llama_model_n_embd (model)},
  1955. {"n_params", llama_model_n_params (model)},
  1956. {"size", llama_model_size (model)},
  1957. };
  1958. }
  1959. int get_slot_n_ctx() {
  1960. return slots.back().n_ctx;
  1961. }
  1962. };
  1963. //
  1964. // server_context (public API)
  1965. //
  1966. server_context::server_context() : impl(new server_context_impl()) {}
  1967. server_context::~server_context() = default;
  1968. void server_context::init() {
  1969. impl->init();
  1970. }
  1971. bool server_context::load_model(const common_params & params) {
  1972. return impl->load_model(params);
  1973. }
  1974. void server_context::start_loop() {
  1975. impl->queue_tasks.start_loop();
  1976. }
  1977. void server_context::terminate() {
  1978. impl->queue_tasks.terminate();
  1979. }
  1980. llama_context * server_context::get_llama_context() const {
  1981. return impl->ctx;
  1982. }
  1983. std::pair<server_queue &, server_response &> server_context::get_queues() {
  1984. return { impl->queue_tasks, impl->queue_results };
  1985. }
  1986. // generator-like API for HTTP response generation
  1987. struct server_res_generator : server_http_res {
  1988. server_response_reader rd;
  1989. server_res_generator(server_context_impl & ctx_server)
  1990. : rd({ctx_server.queue_tasks, ctx_server.queue_results}, HTTP_POLLING_SECONDS) {}
  1991. void ok(const json & response_data) {
  1992. status = 200;
  1993. data = safe_json_to_str(response_data);
  1994. }
  1995. void error(const json & error_data) {
  1996. status = json_value(error_data, "code", 500);
  1997. data = safe_json_to_str({{ "error", error_data }});
  1998. }
  1999. };
  2000. //
  2001. // server_routes
  2002. //
  2003. static std::unique_ptr<server_res_generator> handle_completions_impl(
  2004. server_context_impl & ctx_server,
  2005. server_task_type type,
  2006. const json & data,
  2007. const std::vector<raw_buffer> & files,
  2008. const std::function<bool()> & should_stop,
  2009. task_response_type res_type) {
  2010. GGML_ASSERT(type == SERVER_TASK_TYPE_COMPLETION || type == SERVER_TASK_TYPE_INFILL);
  2011. auto res = std::make_unique<server_res_generator>(ctx_server);
  2012. auto completion_id = gen_chatcmplid();
  2013. auto & rd = res->rd;
  2014. try {
  2015. std::vector<server_task> tasks;
  2016. const auto & prompt = data.at("prompt");
  2017. // TODO: this log can become very long, put it behind a flag or think about a more compact format
  2018. //SRV_DBG("Prompt: %s\n", prompt.is_string() ? prompt.get<std::string>().c_str() : prompt.dump(2).c_str());
  2019. // process prompt
  2020. std::vector<server_tokens> inputs;
  2021. if (res_type != TASK_RESPONSE_TYPE_NONE && ctx_server.mctx != nullptr) {
  2022. // This is the case used by OAI compatible chat path with MTMD. TODO It can be moved to the path below.
  2023. inputs.push_back(process_mtmd_prompt(ctx_server.mctx, prompt.get<std::string>(), files));
  2024. } else {
  2025. // Everything else, including multimodal completions.
  2026. inputs = tokenize_input_prompts(ctx_server.vocab, ctx_server.mctx, prompt, true, true);
  2027. }
  2028. tasks.reserve(inputs.size());
  2029. for (size_t i = 0; i < inputs.size(); i++) {
  2030. server_task task = server_task(type);
  2031. task.id = ctx_server.queue_tasks.get_new_id();
  2032. task.index = i;
  2033. task.tokens = std::move(inputs[i]);
  2034. task.params = server_task::params_from_json_cmpl(
  2035. ctx_server.ctx,
  2036. ctx_server.params_base,
  2037. data);
  2038. task.id_slot = json_value(data, "id_slot", -1);
  2039. // OAI-compat
  2040. task.params.res_type = res_type;
  2041. task.params.oaicompat_cmpl_id = completion_id;
  2042. // oaicompat_model is already populated by params_from_json_cmpl
  2043. tasks.push_back(std::move(task));
  2044. }
  2045. rd.post_tasks(std::move(tasks));
  2046. } catch (const std::exception & e) {
  2047. res->error(format_error_response(e.what(), ERROR_TYPE_INVALID_REQUEST));
  2048. return res;
  2049. }
  2050. bool stream = json_value(data, "stream", false);
  2051. if (!stream) {
  2052. // non-stream, wait for the results
  2053. auto all_results = rd.wait_for_all(should_stop);
  2054. if (all_results.is_terminated) {
  2055. return res; // connection is closed
  2056. } else if (all_results.error) {
  2057. res->error(all_results.error->to_json());
  2058. return res;
  2059. } else {
  2060. json arr = json::array();
  2061. for (auto & res : all_results.results) {
  2062. GGML_ASSERT(dynamic_cast<server_task_result_cmpl_final*>(res.get()) != nullptr);
  2063. arr.push_back(res->to_json());
  2064. }
  2065. // if single request, return single object instead of array
  2066. res->ok(arr.size() == 1 ? arr[0] : arr);
  2067. }
  2068. } else {
  2069. // in streaming mode, the first error must be treated as non-stream response
  2070. // this is to match the OAI API behavior
  2071. // ref: https://github.com/ggml-org/llama.cpp/pull/16486#discussion_r2419657309
  2072. server_task_result_ptr first_result = rd.next(should_stop);
  2073. if (first_result == nullptr) {
  2074. return res; // connection is closed
  2075. } else if (first_result->is_error()) {
  2076. res->error(first_result->to_json());
  2077. return res;
  2078. } else {
  2079. GGML_ASSERT(
  2080. dynamic_cast<server_task_result_cmpl_partial*>(first_result.get()) != nullptr
  2081. || dynamic_cast<server_task_result_cmpl_final*>(first_result.get()) != nullptr
  2082. );
  2083. }
  2084. // next responses are streamed
  2085. if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) {
  2086. res->data = format_anthropic_sse(first_result->to_json());
  2087. } else {
  2088. res->data = format_oai_sse(first_result->to_json()); // to be sent immediately
  2089. }
  2090. res->status = 200;
  2091. res->content_type = "text/event-stream";
  2092. res->next = [res_this = res.get(), res_type, &should_stop](std::string & output) -> bool {
  2093. if (should_stop()) {
  2094. SRV_DBG("%s", "stopping streaming due to should_stop condition\n");
  2095. return false; // should_stop condition met
  2096. }
  2097. if (!res_this->data.empty()) {
  2098. // flush the first chunk
  2099. output = std::move(res_this->data);
  2100. res_this->data.clear();
  2101. return true;
  2102. }
  2103. server_response_reader & rd = res_this->rd;
  2104. // check if there is more data
  2105. if (!rd.has_next()) {
  2106. if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) {
  2107. // Anthropic doesn't send [DONE], message_stop was already sent
  2108. output = "";
  2109. } else if (res_type != TASK_RESPONSE_TYPE_NONE) {
  2110. output = "data: [DONE]\n\n";
  2111. } else {
  2112. output = "";
  2113. }
  2114. SRV_DBG("%s", "all results received, terminating stream\n");
  2115. return false; // no more data, terminate
  2116. }
  2117. // receive subsequent results
  2118. auto result = rd.next(should_stop);
  2119. if (result == nullptr) {
  2120. SRV_DBG("%s", "stopping streaming due to should_stop condition\n");
  2121. return false; // should_stop condition met
  2122. }
  2123. // send the results
  2124. json res_json = result->to_json();
  2125. if (result->is_error()) {
  2126. if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) {
  2127. output = format_anthropic_sse({
  2128. {"event", "error"},
  2129. {"data", res_json},
  2130. });
  2131. } else {
  2132. output = format_oai_sse(json {{ "error", res_json }});
  2133. }
  2134. SRV_DBG("%s", "error received during streaming, terminating stream\n");
  2135. return false; // terminate on error
  2136. } else {
  2137. GGML_ASSERT(
  2138. dynamic_cast<server_task_result_cmpl_partial*>(result.get()) != nullptr
  2139. || dynamic_cast<server_task_result_cmpl_final*>(result.get()) != nullptr
  2140. );
  2141. if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) {
  2142. output = format_anthropic_sse(res_json);
  2143. } else {
  2144. output = format_oai_sse(res_json);
  2145. }
  2146. }
  2147. // has next data, continue
  2148. return true;
  2149. };
  2150. }
  2151. return res;
  2152. }
  2153. void server_routes::init_routes() {
  2154. this->get_health = [this](const server_http_req &) {
  2155. // error and loading states are handled by middleware
  2156. auto res = std::make_unique<server_res_generator>(ctx_server);
  2157. res->ok({{"status", "ok"}});
  2158. return res;
  2159. };
  2160. this->get_metrics = [this](const server_http_req &) {
  2161. auto res = std::make_unique<server_res_generator>(ctx_server);
  2162. if (!params.endpoint_metrics) {
  2163. res->error(format_error_response("This server does not support metrics endpoint. Start it with `--metrics`", ERROR_TYPE_NOT_SUPPORTED));
  2164. return res;
  2165. }
  2166. // request slots data using task queue
  2167. // TODO: use server_response_reader
  2168. int task_id = ctx_server.queue_tasks.get_new_id();
  2169. {
  2170. server_task task(SERVER_TASK_TYPE_METRICS);
  2171. task.id = task_id;
  2172. ctx_server.queue_results.add_waiting_task_id(task_id);
  2173. ctx_server.queue_tasks.post(std::move(task), true); // high-priority task
  2174. }
  2175. // get the result
  2176. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  2177. ctx_server.queue_results.remove_waiting_task_id(task_id);
  2178. if (result->is_error()) {
  2179. res->error(result->to_json());
  2180. return res;
  2181. }
  2182. // TODO: get rid of this dynamic_cast
  2183. auto res_task = dynamic_cast<server_task_result_metrics*>(result.get());
  2184. GGML_ASSERT(res_task != nullptr);
  2185. // metrics definition: https://prometheus.io/docs/practices/naming/#metric-names
  2186. json all_metrics_def = json {
  2187. {"counter", {{
  2188. {"name", "prompt_tokens_total"},
  2189. {"help", "Number of prompt tokens processed."},
  2190. {"value", (uint64_t) res_task->n_prompt_tokens_processed_total}
  2191. }, {
  2192. {"name", "prompt_seconds_total"},
  2193. {"help", "Prompt process time"},
  2194. {"value", (uint64_t) res_task->t_prompt_processing_total / 1.e3}
  2195. }, {
  2196. {"name", "tokens_predicted_total"},
  2197. {"help", "Number of generation tokens processed."},
  2198. {"value", (uint64_t) res_task->n_tokens_predicted_total}
  2199. }, {
  2200. {"name", "tokens_predicted_seconds_total"},
  2201. {"help", "Predict process time"},
  2202. {"value", (uint64_t) res_task->t_tokens_generation_total / 1.e3}
  2203. }, {
  2204. {"name", "n_decode_total"},
  2205. {"help", "Total number of llama_decode() calls"},
  2206. {"value", res_task->n_decode_total}
  2207. }, {
  2208. {"name", "n_tokens_max"},
  2209. {"help", "Largest observed n_tokens."},
  2210. {"value", res_task->n_tokens_max}
  2211. }, {
  2212. {"name", "n_busy_slots_per_decode"},
  2213. {"help", "Average number of busy slots per llama_decode() call"},
  2214. {"value", (float) res_task->n_busy_slots_total / std::max((float) res_task->n_decode_total, 1.f)}
  2215. }}},
  2216. {"gauge", {{
  2217. {"name", "prompt_tokens_seconds"},
  2218. {"help", "Average prompt throughput in tokens/s."},
  2219. {"value", res_task->n_prompt_tokens_processed ? 1.e3 / res_task->t_prompt_processing * res_task->n_prompt_tokens_processed : 0.}
  2220. },{
  2221. {"name", "predicted_tokens_seconds"},
  2222. {"help", "Average generation throughput in tokens/s."},
  2223. {"value", res_task->n_tokens_predicted ? 1.e3 / res_task->t_tokens_generation * res_task->n_tokens_predicted : 0.}
  2224. },{
  2225. {"name", "requests_processing"},
  2226. {"help", "Number of requests processing."},
  2227. {"value", (uint64_t) res_task->n_processing_slots}
  2228. },{
  2229. {"name", "requests_deferred"},
  2230. {"help", "Number of requests deferred."},
  2231. {"value", (uint64_t) res_task->n_tasks_deferred}
  2232. }}}
  2233. };
  2234. std::stringstream prometheus;
  2235. for (const auto & el : all_metrics_def.items()) {
  2236. const auto & type = el.key();
  2237. const auto & metrics_def = el.value();
  2238. for (const auto & metric_def : metrics_def) {
  2239. const std::string name = metric_def.at("name");
  2240. const std::string help = metric_def.at("help");
  2241. auto value = json_value(metric_def, "value", 0.);
  2242. prometheus << "# HELP llamacpp:" << name << " " << help << "\n"
  2243. << "# TYPE llamacpp:" << name << " " << type << "\n"
  2244. << "llamacpp:" << name << " " << value << "\n";
  2245. }
  2246. }
  2247. res->headers["Process-Start-Time-Unix"] = std::to_string(res_task->t_start);
  2248. res->content_type = "text/plain; version=0.0.4";
  2249. res->status = 200;
  2250. res->data = prometheus.str();
  2251. return res;
  2252. };
  2253. this->get_slots = [this](const server_http_req & req) {
  2254. auto res = std::make_unique<server_res_generator>(ctx_server);
  2255. if (!params.endpoint_slots) {
  2256. res->error(format_error_response("This server does not support slots endpoint. Start it with `--slots`", ERROR_TYPE_NOT_SUPPORTED));
  2257. return res;
  2258. }
  2259. // request slots data using task queue
  2260. int task_id = ctx_server.queue_tasks.get_new_id();
  2261. {
  2262. server_task task(SERVER_TASK_TYPE_METRICS);
  2263. task.id = task_id;
  2264. ctx_server.queue_results.add_waiting_task_id(task_id);
  2265. ctx_server.queue_tasks.post(std::move(task), true); // high-priority task
  2266. }
  2267. // get the result
  2268. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  2269. ctx_server.queue_results.remove_waiting_task_id(task_id);
  2270. if (result->is_error()) {
  2271. res->error(result->to_json());
  2272. return res;
  2273. }
  2274. // TODO: get rid of this dynamic_cast
  2275. auto res_task = dynamic_cast<server_task_result_metrics*>(result.get());
  2276. GGML_ASSERT(res_task != nullptr);
  2277. // optionally return "fail_on_no_slot" error
  2278. if (!req.get_param("fail_on_no_slot").empty()) {
  2279. if (res_task->n_idle_slots == 0) {
  2280. res->error(format_error_response("no slot available", ERROR_TYPE_UNAVAILABLE));
  2281. return res;
  2282. }
  2283. }
  2284. res->ok(res_task->slots_data);
  2285. return res;
  2286. };
  2287. this->post_slots = [this](const server_http_req & req) {
  2288. auto res = std::make_unique<server_res_generator>(ctx_server);
  2289. if (params.slot_save_path.empty()) {
  2290. res->error(format_error_response("This server does not support slots action. Start it with `--slot-save-path`", ERROR_TYPE_NOT_SUPPORTED));
  2291. return res;
  2292. }
  2293. std::string id_slot_str = req.get_param("id_slot");
  2294. int id_slot;
  2295. try {
  2296. id_slot = std::stoi(id_slot_str);
  2297. } catch (const std::exception &) {
  2298. res->error(format_error_response("Invalid slot ID", ERROR_TYPE_INVALID_REQUEST));
  2299. return res;
  2300. }
  2301. std::string action = req.get_param("action");
  2302. if (action == "save") {
  2303. return handle_slots_save(req, id_slot);
  2304. } else if (action == "restore") {
  2305. return handle_slots_restore(req, id_slot);
  2306. } else if (action == "erase") {
  2307. return handle_slots_erase(req, id_slot);
  2308. } else {
  2309. res->error(format_error_response("Invalid action", ERROR_TYPE_INVALID_REQUEST));
  2310. return res;
  2311. }
  2312. };
  2313. this->get_props = [this](const server_http_req &) {
  2314. auto res = std::make_unique<server_res_generator>(ctx_server);
  2315. json default_generation_settings_for_props;
  2316. {
  2317. task_params params;
  2318. params.sampling = ctx_server.params_base.sampling;
  2319. default_generation_settings_for_props = json {
  2320. {"params", params.to_json(true)},
  2321. {"n_ctx", ctx_server.get_slot_n_ctx()},
  2322. };
  2323. }
  2324. // this endpoint is publicly available, please only return what is safe to be exposed
  2325. json data = {
  2326. { "default_generation_settings", default_generation_settings_for_props },
  2327. { "total_slots", ctx_server.params_base.n_parallel },
  2328. { "model_alias", ctx_server.params_base.model_alias },
  2329. { "model_path", ctx_server.params_base.model.path },
  2330. { "modalities", json {
  2331. {"vision", ctx_server.oai_parser_opt.allow_image},
  2332. {"audio", ctx_server.oai_parser_opt.allow_audio},
  2333. } },
  2334. { "endpoint_slots", params.endpoint_slots },
  2335. { "endpoint_props", params.endpoint_props },
  2336. { "endpoint_metrics", params.endpoint_metrics },
  2337. { "webui", params.webui },
  2338. { "chat_template", common_chat_templates_source(ctx_server.chat_templates.get()) },
  2339. { "bos_token", common_token_to_piece(ctx_server.ctx, llama_vocab_bos(ctx_server.vocab), /* special= */ true)},
  2340. { "eos_token", common_token_to_piece(ctx_server.ctx, llama_vocab_eos(ctx_server.vocab), /* special= */ true)},
  2341. { "build_info", build_info },
  2342. };
  2343. if (ctx_server.params_base.use_jinja) {
  2344. if (auto tool_use_src = common_chat_templates_source(ctx_server.chat_templates.get(), "tool_use")) {
  2345. data["chat_template_tool_use"] = tool_use_src;
  2346. }
  2347. }
  2348. res->ok(data);
  2349. return res;
  2350. };
  2351. this->post_props = [this](const server_http_req &) {
  2352. auto res = std::make_unique<server_res_generator>(ctx_server);
  2353. if (!params.endpoint_props) {
  2354. res->error(format_error_response("This server does not support changing global properties. Start it with `--props`", ERROR_TYPE_NOT_SUPPORTED));
  2355. return res;
  2356. }
  2357. // update any props here
  2358. res->ok({{ "success", true }});
  2359. return res;
  2360. };
  2361. this->get_api_show = [this](const server_http_req &) {
  2362. auto res = std::make_unique<server_res_generator>(ctx_server);
  2363. bool has_mtmd = ctx_server.mctx != nullptr;
  2364. json data = {
  2365. {
  2366. "template", common_chat_templates_source(ctx_server.chat_templates.get()),
  2367. },
  2368. {
  2369. "model_info", {
  2370. { "llama.context_length", ctx_server.get_slot_n_ctx() },
  2371. }
  2372. },
  2373. {"modelfile", ""},
  2374. {"parameters", ""},
  2375. {"template", common_chat_templates_source(ctx_server.chat_templates.get())},
  2376. {"details", {
  2377. {"parent_model", ""},
  2378. {"format", "gguf"},
  2379. {"family", ""},
  2380. {"families", {""}},
  2381. {"parameter_size", ""},
  2382. {"quantization_level", ""}
  2383. }},
  2384. {"model_info", ""},
  2385. {"capabilities", has_mtmd ? json({"completion","multimodal"}) : json({"completion"})}
  2386. };
  2387. res->ok(data);
  2388. return res;
  2389. };
  2390. this->post_infill = [this](const server_http_req & req) {
  2391. auto res = std::make_unique<server_res_generator>(ctx_server);
  2392. // check model compatibility
  2393. std::string err;
  2394. if (llama_vocab_fim_pre(ctx_server.vocab) == LLAMA_TOKEN_NULL) {
  2395. err += "prefix token is missing. ";
  2396. }
  2397. if (llama_vocab_fim_suf(ctx_server.vocab) == LLAMA_TOKEN_NULL) {
  2398. err += "suffix token is missing. ";
  2399. }
  2400. if (llama_vocab_fim_mid(ctx_server.vocab) == LLAMA_TOKEN_NULL) {
  2401. err += "middle token is missing. ";
  2402. }
  2403. if (!err.empty()) {
  2404. res->error(format_error_response(string_format("Infill is not supported by this model: %s", err.c_str()), ERROR_TYPE_NOT_SUPPORTED));
  2405. return res;
  2406. }
  2407. // validate input
  2408. json data = json::parse(req.body);
  2409. if (data.contains("prompt") && !data.at("prompt").is_string()) {
  2410. // prompt is optional
  2411. res->error(format_error_response("\"prompt\" must be a string", ERROR_TYPE_INVALID_REQUEST));
  2412. }
  2413. if (!data.contains("input_prefix")) {
  2414. res->error(format_error_response("\"input_prefix\" is required", ERROR_TYPE_INVALID_REQUEST));
  2415. }
  2416. if (!data.contains("input_suffix")) {
  2417. res->error(format_error_response("\"input_suffix\" is required", ERROR_TYPE_INVALID_REQUEST));
  2418. }
  2419. if (data.contains("input_extra") && !data.at("input_extra").is_array()) {
  2420. // input_extra is optional
  2421. res->error(format_error_response("\"input_extra\" must be an array of {\"filename\": string, \"text\": string}", ERROR_TYPE_INVALID_REQUEST));
  2422. return res;
  2423. }
  2424. json input_extra = json_value(data, "input_extra", json::array());
  2425. for (const auto & chunk : input_extra) {
  2426. // { "text": string, "filename": string }
  2427. if (!chunk.contains("text") || !chunk.at("text").is_string()) {
  2428. res->error(format_error_response("extra_context chunk must contain a \"text\" field with a string value", ERROR_TYPE_INVALID_REQUEST));
  2429. return res;
  2430. }
  2431. // filename is optional
  2432. if (chunk.contains("filename") && !chunk.at("filename").is_string()) {
  2433. res->error(format_error_response("extra_context chunk's \"filename\" field must be a string", ERROR_TYPE_INVALID_REQUEST));
  2434. return res;
  2435. }
  2436. }
  2437. data["input_extra"] = input_extra; // default to empty array if it's not exist
  2438. std::string prompt = json_value(data, "prompt", std::string());
  2439. std::vector<server_tokens> tokenized_prompts = tokenize_input_prompts(ctx_server.vocab, ctx_server.mctx, prompt, false, true);
  2440. SRV_DBG("creating infill tasks, n_prompts = %d\n", (int) tokenized_prompts.size());
  2441. data["prompt"] = format_prompt_infill(
  2442. ctx_server.vocab,
  2443. data.at("input_prefix"),
  2444. data.at("input_suffix"),
  2445. data.at("input_extra"),
  2446. ctx_server.params_base.n_batch,
  2447. ctx_server.params_base.n_predict,
  2448. ctx_server.get_slot_n_ctx(),
  2449. ctx_server.params_base.spm_infill,
  2450. tokenized_prompts[0].get_text_tokens() // TODO: this could maybe be multimodal.
  2451. );
  2452. std::vector<raw_buffer> files; // dummy
  2453. return handle_completions_impl(
  2454. ctx_server,
  2455. SERVER_TASK_TYPE_INFILL,
  2456. data,
  2457. files,
  2458. req.should_stop,
  2459. TASK_RESPONSE_TYPE_NONE); // infill is not OAI compatible
  2460. };
  2461. this->post_completions = [this](const server_http_req & req) {
  2462. std::vector<raw_buffer> files; // dummy
  2463. const json body = json::parse(req.body);
  2464. return handle_completions_impl(
  2465. ctx_server,
  2466. SERVER_TASK_TYPE_COMPLETION,
  2467. body,
  2468. files,
  2469. req.should_stop,
  2470. TASK_RESPONSE_TYPE_NONE);
  2471. };
  2472. this->post_completions_oai = [this](const server_http_req & req) {
  2473. std::vector<raw_buffer> files; // dummy
  2474. const json body = json::parse(req.body);
  2475. return handle_completions_impl(
  2476. ctx_server,
  2477. SERVER_TASK_TYPE_COMPLETION,
  2478. body,
  2479. files,
  2480. req.should_stop,
  2481. TASK_RESPONSE_TYPE_OAI_CMPL);
  2482. };
  2483. this->post_chat_completions = [this](const server_http_req & req) {
  2484. std::vector<raw_buffer> files;
  2485. json body = json::parse(req.body);
  2486. json body_parsed = oaicompat_chat_params_parse(
  2487. body,
  2488. ctx_server.oai_parser_opt,
  2489. files);
  2490. return handle_completions_impl(
  2491. ctx_server,
  2492. SERVER_TASK_TYPE_COMPLETION,
  2493. body_parsed,
  2494. files,
  2495. req.should_stop,
  2496. TASK_RESPONSE_TYPE_OAI_CHAT);
  2497. };
  2498. this->post_anthropic_messages = [this](const server_http_req & req) {
  2499. std::vector<raw_buffer> files;
  2500. json body = convert_anthropic_to_oai(json::parse(req.body));
  2501. json body_parsed = oaicompat_chat_params_parse(
  2502. body,
  2503. ctx_server.oai_parser_opt,
  2504. files);
  2505. return handle_completions_impl(
  2506. ctx_server,
  2507. SERVER_TASK_TYPE_COMPLETION,
  2508. body_parsed,
  2509. files,
  2510. req.should_stop,
  2511. TASK_RESPONSE_TYPE_ANTHROPIC);
  2512. };
  2513. this->post_anthropic_count_tokens = [this](const server_http_req & req) {
  2514. auto res = std::make_unique<server_res_generator>(ctx_server);
  2515. std::vector<raw_buffer> files;
  2516. json body = convert_anthropic_to_oai(json::parse(req.body));
  2517. json body_parsed = oaicompat_chat_params_parse(
  2518. body,
  2519. ctx_server.oai_parser_opt,
  2520. files);
  2521. json prompt = body_parsed.at("prompt");
  2522. llama_tokens tokens = tokenize_mixed(ctx_server.vocab, prompt, true, true);
  2523. res->ok({{"input_tokens", static_cast<int>(tokens.size())}});
  2524. return res;
  2525. };
  2526. // same with handle_chat_completions, but without inference part
  2527. this->post_apply_template = [this](const server_http_req & req) {
  2528. auto res = std::make_unique<server_res_generator>(ctx_server);
  2529. std::vector<raw_buffer> files; // dummy, unused
  2530. json body = json::parse(req.body);
  2531. json data = oaicompat_chat_params_parse(
  2532. body,
  2533. ctx_server.oai_parser_opt,
  2534. files);
  2535. res->ok({{ "prompt", std::move(data.at("prompt")) }});
  2536. return res;
  2537. };
  2538. this->get_models = [this](const server_http_req &) {
  2539. auto res = std::make_unique<server_res_generator>(ctx_server);
  2540. json model_meta = nullptr;
  2541. if (is_ready()) {
  2542. model_meta = ctx_server.model_meta();
  2543. }
  2544. bool has_mtmd = ctx_server.mctx != nullptr;
  2545. json models = {
  2546. {"models", {
  2547. {
  2548. {"name", params.model_alias.empty() ? params.model.path : params.model_alias},
  2549. {"model", params.model_alias.empty() ? params.model.path : params.model_alias},
  2550. {"modified_at", ""},
  2551. {"size", ""},
  2552. {"digest", ""}, // dummy value, llama.cpp does not support managing model file's hash
  2553. {"type", "model"},
  2554. {"description", ""},
  2555. {"tags", {""}},
  2556. {"capabilities", has_mtmd ? json({"completion","multimodal"}) : json({"completion"})},
  2557. {"parameters", ""},
  2558. {"details", {
  2559. {"parent_model", ""},
  2560. {"format", "gguf"},
  2561. {"family", ""},
  2562. {"families", {""}},
  2563. {"parameter_size", ""},
  2564. {"quantization_level", ""}
  2565. }}
  2566. }
  2567. }},
  2568. {"object", "list"},
  2569. {"data", {
  2570. {
  2571. {"id", params.model_alias.empty() ? params.model.path : params.model_alias},
  2572. {"object", "model"},
  2573. {"created", std::time(0)},
  2574. {"owned_by", "llamacpp"},
  2575. {"meta", model_meta},
  2576. },
  2577. }}
  2578. };
  2579. res->ok(models);
  2580. return res;
  2581. };
  2582. this->post_tokenize = [this](const server_http_req & req) {
  2583. auto res = std::make_unique<server_res_generator>(ctx_server);
  2584. const json body = json::parse(req.body);
  2585. json tokens_response = json::array();
  2586. if (body.count("content") != 0) {
  2587. const bool add_special = json_value(body, "add_special", false);
  2588. const bool parse_special = json_value(body, "parse_special", true);
  2589. const bool with_pieces = json_value(body, "with_pieces", false);
  2590. llama_tokens tokens = tokenize_mixed(ctx_server.vocab, body.at("content"), add_special, parse_special);
  2591. if (with_pieces) {
  2592. for (const auto& token : tokens) {
  2593. std::string piece = common_token_to_piece(ctx_server.ctx, token);
  2594. json piece_json;
  2595. // Check if the piece is valid UTF-8
  2596. if (is_valid_utf8(piece)) {
  2597. piece_json = piece;
  2598. } else {
  2599. // If not valid UTF-8, store as array of byte values
  2600. piece_json = json::array();
  2601. for (unsigned char c : piece) {
  2602. piece_json.push_back(static_cast<int>(c));
  2603. }
  2604. }
  2605. tokens_response.push_back({
  2606. {"id", token},
  2607. {"piece", piece_json}
  2608. });
  2609. }
  2610. } else {
  2611. tokens_response = tokens;
  2612. }
  2613. }
  2614. res->ok(json{{"tokens", std::move(tokens_response)}});
  2615. return res;
  2616. };
  2617. this->post_detokenize = [this](const server_http_req & req) {
  2618. auto res = std::make_unique<server_res_generator>(ctx_server);
  2619. const json body = json::parse(req.body);
  2620. std::string content;
  2621. if (body.count("tokens") != 0) {
  2622. const llama_tokens tokens = body.at("tokens");
  2623. content = tokens_to_str(ctx_server.ctx, tokens);
  2624. }
  2625. res->ok(json{{"content", std::move(content)}});
  2626. return res;
  2627. };
  2628. this->post_embeddings = [this](const server_http_req & req) {
  2629. return handle_embeddings_impl(req, TASK_RESPONSE_TYPE_NONE);
  2630. };
  2631. this->post_embeddings_oai = [this](const server_http_req & req) {
  2632. return handle_embeddings_impl(req, TASK_RESPONSE_TYPE_OAI_EMBD);
  2633. };
  2634. this->post_rerank = [this](const server_http_req & req) {
  2635. auto res = std::make_unique<server_res_generator>(ctx_server);
  2636. if (!ctx_server.params_base.embedding || ctx_server.params_base.pooling_type != LLAMA_POOLING_TYPE_RANK) {
  2637. res->error(format_error_response("This server does not support reranking. Start it with `--reranking`", ERROR_TYPE_NOT_SUPPORTED));
  2638. return res;
  2639. }
  2640. const json body = json::parse(req.body);
  2641. // if true, use TEI API format, otherwise use Jina API format
  2642. // Jina: https://jina.ai/reranker/
  2643. // TEI: https://huggingface.github.io/text-embeddings-inference/#/Text%20Embeddings%20Inference/rerank
  2644. bool is_tei_format = body.contains("texts");
  2645. json query;
  2646. if (body.count("query") == 1) {
  2647. query = body.at("query");
  2648. if (!query.is_string()) {
  2649. res->error(format_error_response("\"query\" must be a string", ERROR_TYPE_INVALID_REQUEST));
  2650. return res;
  2651. }
  2652. } else {
  2653. res->error(format_error_response("\"query\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  2654. return res;
  2655. }
  2656. std::vector<std::string> documents = json_value(body, "documents",
  2657. json_value(body, "texts", std::vector<std::string>()));
  2658. if (documents.empty()) {
  2659. res->error(format_error_response("\"documents\" must be a non-empty string array", ERROR_TYPE_INVALID_REQUEST));
  2660. return res;
  2661. }
  2662. int top_n = json_value(body, "top_n", (int)documents.size());
  2663. // create and queue the task
  2664. json responses = json::array();
  2665. server_response_reader rd({ctx_server.queue_tasks, ctx_server.queue_results}, HTTP_POLLING_SECONDS);
  2666. {
  2667. std::vector<server_task> tasks;
  2668. tasks.reserve(documents.size());
  2669. for (size_t i = 0; i < documents.size(); i++) {
  2670. auto tmp = format_prompt_rerank(ctx_server.model, ctx_server.vocab, ctx_server.mctx, query, documents[i]);
  2671. server_task task = server_task(SERVER_TASK_TYPE_RERANK);
  2672. task.id = ctx_server.queue_tasks.get_new_id();
  2673. task.index = i;
  2674. task.tokens = std::move(tmp);
  2675. tasks.push_back(std::move(task));
  2676. }
  2677. rd.post_tasks(std::move(tasks));
  2678. }
  2679. // wait for the results
  2680. auto all_results = rd.wait_for_all(req.should_stop);
  2681. // collect results
  2682. if (all_results.is_terminated) {
  2683. return res; // connection is closed
  2684. } else if (all_results.error) {
  2685. res->error(all_results.error->to_json());
  2686. return res;
  2687. } else {
  2688. for (auto & res : all_results.results) {
  2689. GGML_ASSERT(dynamic_cast<server_task_result_rerank*>(res.get()) != nullptr);
  2690. responses.push_back(res->to_json());
  2691. }
  2692. }
  2693. // write JSON response
  2694. json root = format_response_rerank(
  2695. body,
  2696. responses,
  2697. is_tei_format,
  2698. documents,
  2699. top_n);
  2700. res->ok(root);
  2701. return res;
  2702. };
  2703. this->get_lora_adapters = [this](const server_http_req &) {
  2704. auto res = std::make_unique<server_res_generator>(ctx_server);
  2705. json result = json::array();
  2706. const auto & loras = ctx_server.params_base.lora_adapters;
  2707. for (size_t i = 0; i < loras.size(); ++i) {
  2708. auto & lora = loras[i];
  2709. json entry = {
  2710. {"id", i},
  2711. {"path", lora.path},
  2712. {"scale", lora.scale},
  2713. {"task_name", lora.task_name},
  2714. {"prompt_prefix", lora.prompt_prefix},
  2715. };
  2716. std::string alora_invocation_string = "";
  2717. const uint64_t n_alora_tokens = llama_adapter_get_alora_n_invocation_tokens(lora.ptr);
  2718. std::vector<llama_token> alora_invocation_tokens;
  2719. if (n_alora_tokens) {
  2720. const llama_token * alora_tokens = llama_adapter_get_alora_invocation_tokens(lora.ptr);
  2721. for (uint64_t i = 0; i < n_alora_tokens; ++i) {
  2722. alora_invocation_string += common_token_to_piece(ctx_server.ctx, alora_tokens[i]);
  2723. alora_invocation_tokens.push_back(alora_tokens[i]);
  2724. }
  2725. entry["alora_invocation_string"] = alora_invocation_string;
  2726. entry["alora_invocation_tokens"] = alora_invocation_tokens;
  2727. }
  2728. result.push_back(std::move(entry));
  2729. }
  2730. res->ok(result);
  2731. return res;
  2732. };
  2733. this->post_lora_adapters = [this](const server_http_req & req) {
  2734. auto res = std::make_unique<server_res_generator>(ctx_server);
  2735. const json body = json::parse(req.body);
  2736. if (!body.is_array()) {
  2737. res->error(format_error_response("Request body must be an array", ERROR_TYPE_INVALID_REQUEST));
  2738. return res;
  2739. }
  2740. int task_id = ctx_server.queue_tasks.get_new_id();
  2741. {
  2742. server_task task(SERVER_TASK_TYPE_SET_LORA);
  2743. task.id = task_id;
  2744. task.set_lora = parse_lora_request(ctx_server.params_base.lora_adapters, body);
  2745. ctx_server.queue_results.add_waiting_task_id(task_id);
  2746. ctx_server.queue_tasks.post(std::move(task));
  2747. }
  2748. // get the result
  2749. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  2750. ctx_server.queue_results.remove_waiting_task_id(task_id);
  2751. if (result->is_error()) {
  2752. res->error(result->to_json());
  2753. return res;
  2754. }
  2755. GGML_ASSERT(dynamic_cast<server_task_result_apply_lora*>(result.get()) != nullptr);
  2756. res->ok(result->to_json());
  2757. return res;
  2758. };
  2759. }
  2760. std::unique_ptr<server_res_generator> server_routes::handle_slots_save(const server_http_req & req, int id_slot) {
  2761. auto res = std::make_unique<server_res_generator>(ctx_server);
  2762. const json request_data = json::parse(req.body);
  2763. std::string filename = request_data.at("filename");
  2764. if (!fs_validate_filename(filename)) {
  2765. res->error(format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  2766. return res;
  2767. }
  2768. std::string filepath = params.slot_save_path + filename;
  2769. int task_id = ctx_server.queue_tasks.get_new_id();
  2770. {
  2771. server_task task(SERVER_TASK_TYPE_SLOT_SAVE);
  2772. task.id = task_id;
  2773. task.slot_action.slot_id = id_slot;
  2774. task.slot_action.filename = filename;
  2775. task.slot_action.filepath = filepath;
  2776. // TODO: use server_response_reader
  2777. ctx_server.queue_results.add_waiting_task_id(task_id);
  2778. ctx_server.queue_tasks.post(std::move(task));
  2779. }
  2780. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  2781. ctx_server.queue_results.remove_waiting_task_id(task_id);
  2782. if (result->is_error()) {
  2783. res->error(result->to_json());
  2784. return res;
  2785. }
  2786. res->ok(result->to_json());
  2787. return res;
  2788. }
  2789. std::unique_ptr<server_res_generator> server_routes::handle_slots_restore(const server_http_req & req, int id_slot) {
  2790. auto res = std::make_unique<server_res_generator>(ctx_server);
  2791. const json request_data = json::parse(req.body);
  2792. std::string filename = request_data.at("filename");
  2793. if (!fs_validate_filename(filename)) {
  2794. res->error(format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  2795. return res;
  2796. }
  2797. std::string filepath = params.slot_save_path + filename;
  2798. int task_id = ctx_server.queue_tasks.get_new_id();
  2799. {
  2800. server_task task(SERVER_TASK_TYPE_SLOT_RESTORE);
  2801. task.id = task_id;
  2802. task.slot_action.slot_id = id_slot;
  2803. task.slot_action.filename = filename;
  2804. task.slot_action.filepath = filepath;
  2805. // TODO: use server_response_reader
  2806. ctx_server.queue_results.add_waiting_task_id(task_id);
  2807. ctx_server.queue_tasks.post(std::move(task));
  2808. }
  2809. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  2810. ctx_server.queue_results.remove_waiting_task_id(task_id);
  2811. if (result->is_error()) {
  2812. res->error(result->to_json());
  2813. return res;
  2814. }
  2815. GGML_ASSERT(dynamic_cast<server_task_result_slot_save_load*>(result.get()) != nullptr);
  2816. res->ok(result->to_json());
  2817. return res;
  2818. }
  2819. std::unique_ptr<server_res_generator> server_routes::handle_slots_erase(const server_http_req &, int id_slot) {
  2820. auto res = std::make_unique<server_res_generator>(ctx_server);
  2821. int task_id = ctx_server.queue_tasks.get_new_id();
  2822. {
  2823. server_task task(SERVER_TASK_TYPE_SLOT_ERASE);
  2824. task.id = task_id;
  2825. task.slot_action.slot_id = id_slot;
  2826. // TODO: use server_response_reader
  2827. ctx_server.queue_results.add_waiting_task_id(task_id);
  2828. ctx_server.queue_tasks.post(std::move(task));
  2829. }
  2830. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  2831. ctx_server.queue_results.remove_waiting_task_id(task_id);
  2832. if (result->is_error()) {
  2833. res->error(result->to_json());
  2834. return res;
  2835. }
  2836. GGML_ASSERT(dynamic_cast<server_task_result_slot_erase*>(result.get()) != nullptr);
  2837. res->ok(result->to_json());
  2838. return res;
  2839. }
  2840. std::unique_ptr<server_res_generator> server_routes::handle_embeddings_impl(const server_http_req & req, task_response_type res_type) {
  2841. auto res = std::make_unique<server_res_generator>(ctx_server);
  2842. if (!ctx_server.params_base.embedding) {
  2843. res->error(format_error_response("This server does not support embeddings. Start it with `--embeddings`", ERROR_TYPE_NOT_SUPPORTED));
  2844. return res;
  2845. }
  2846. if (res_type != TASK_RESPONSE_TYPE_NONE && llama_pooling_type(ctx_server.ctx) == LLAMA_POOLING_TYPE_NONE) {
  2847. res->error(format_error_response("Pooling type 'none' is not OAI compatible. Please use a different pooling type", ERROR_TYPE_INVALID_REQUEST));
  2848. return res;
  2849. }
  2850. const json body = json::parse(req.body);
  2851. // for the shape of input/content, see tokenize_input_prompts()
  2852. json prompt;
  2853. if (body.count("input") != 0) {
  2854. prompt = body.at("input");
  2855. } else if (body.contains("content")) {
  2856. res_type = TASK_RESPONSE_TYPE_NONE; // "content" field is not OAI compatible
  2857. prompt = body.at("content");
  2858. } else {
  2859. res->error(format_error_response("\"input\" or \"content\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  2860. return res;
  2861. }
  2862. bool use_base64 = false;
  2863. if (body.count("encoding_format") != 0) {
  2864. const std::string& format = body.at("encoding_format");
  2865. if (format == "base64") {
  2866. use_base64 = true;
  2867. } else if (format != "float") {
  2868. res->error(format_error_response("The format to return the embeddings in. Can be either float or base64", ERROR_TYPE_INVALID_REQUEST));
  2869. return res;
  2870. }
  2871. }
  2872. auto tokenized_prompts = tokenize_input_prompts(ctx_server.vocab, ctx_server.mctx, prompt, true, true);
  2873. for (const auto & tokens : tokenized_prompts) {
  2874. // this check is necessary for models that do not add BOS token to the input
  2875. if (tokens.empty()) {
  2876. res->error(format_error_response("Input content cannot be empty", ERROR_TYPE_INVALID_REQUEST));
  2877. return res;
  2878. }
  2879. }
  2880. int embd_normalize = 2; // default to Euclidean/L2 norm
  2881. if (body.count("embd_normalize") != 0) {
  2882. embd_normalize = body.at("embd_normalize");
  2883. if (llama_pooling_type(ctx_server.ctx) == LLAMA_POOLING_TYPE_NONE) {
  2884. SRV_DBG("embd_normalize is not supported by pooling type %d, ignoring it\n", llama_pooling_type(ctx_server.ctx));
  2885. }
  2886. }
  2887. // create and queue the task
  2888. json responses = json::array();
  2889. server_response_reader rd({ctx_server.queue_tasks, ctx_server.queue_results}, HTTP_POLLING_SECONDS);
  2890. {
  2891. std::vector<server_task> tasks;
  2892. for (size_t i = 0; i < tokenized_prompts.size(); i++) {
  2893. server_task task = server_task(SERVER_TASK_TYPE_EMBEDDING);
  2894. task.id = ctx_server.queue_tasks.get_new_id();
  2895. task.index = i;
  2896. task.tokens = std::move(tokenized_prompts[i]);
  2897. // OAI-compat
  2898. task.params.res_type = res_type;
  2899. task.params.embd_normalize = embd_normalize;
  2900. tasks.push_back(std::move(task));
  2901. }
  2902. rd.post_tasks(std::move(tasks));
  2903. }
  2904. // wait for the results
  2905. auto all_results = rd.wait_for_all(req.should_stop);
  2906. // collect results
  2907. if (all_results.is_terminated) {
  2908. return res; // connection is closed
  2909. } else if (all_results.error) {
  2910. res->error(all_results.error->to_json());
  2911. return res;
  2912. } else {
  2913. for (auto & res : all_results.results) {
  2914. GGML_ASSERT(dynamic_cast<server_task_result_embd*>(res.get()) != nullptr);
  2915. responses.push_back(res->to_json());
  2916. }
  2917. }
  2918. // write JSON response
  2919. json root = res_type == TASK_RESPONSE_TYPE_OAI_EMBD
  2920. ? format_embeddings_response_oaicompat(body, responses, use_base64)
  2921. : json(responses);
  2922. res->ok(root);
  2923. return res;
  2924. }