server-context.cpp 160 KB

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