server-context.cpp 151 KB

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