server-context.cpp 146 KB

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