1
0

server-context.cpp 153 KB

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