1
0

server.cpp 156 KB

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