server-context.cpp 162 KB

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