server-context.cpp 157 KB

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