server-context.cpp 153 KB

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