server-context.cpp 164 KB

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