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