server-context.cpp 154 KB

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