server-context.cpp 163 KB

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