server-context.cpp 150 KB

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