server-context.cpp 146 KB

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