server-context.cpp 162 KB

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