server-context.cpp 164 KB

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