1
0

server.cpp 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461
  1. #include "utils.hpp"
  2. #include "arg.h"
  3. #include "common.h"
  4. #include "json-schema-to-grammar.h"
  5. #include "llama.h"
  6. #include "log.h"
  7. #include "sampling.h"
  8. #include "speculative.h"
  9. // Change JSON_ASSERT from assert() to GGML_ASSERT:
  10. #define JSON_ASSERT GGML_ASSERT
  11. #include "json.hpp"
  12. // mime type for sending response
  13. #define MIMETYPE_JSON "application/json; charset=utf-8"
  14. // auto generated files (update with ./deps.sh)
  15. #include "index.html.hpp"
  16. #include "loading.html.hpp"
  17. #include <atomic>
  18. #include <condition_variable>
  19. #include <cstddef>
  20. #include <cinttypes>
  21. #include <deque>
  22. #include <memory>
  23. #include <mutex>
  24. #include <signal.h>
  25. #include <thread>
  26. #include <unordered_map>
  27. #include <unordered_set>
  28. using json = nlohmann::ordered_json;
  29. enum stop_type {
  30. STOP_TYPE_FULL,
  31. STOP_TYPE_PARTIAL,
  32. };
  33. // state diagram: https://github.com/ggerganov/llama.cpp/pull/9283
  34. enum slot_state {
  35. SLOT_STATE_IDLE,
  36. SLOT_STATE_STARTED, // TODO: this state is only used for setting up the initial prompt processing; maybe merge it with launch_slot_with_task in the future
  37. SLOT_STATE_PROCESSING_PROMPT,
  38. SLOT_STATE_DONE_PROMPT,
  39. SLOT_STATE_GENERATING,
  40. };
  41. enum server_state {
  42. SERVER_STATE_LOADING_MODEL, // Server is starting up, model not fully loaded yet
  43. SERVER_STATE_READY, // Server is ready and model is loaded
  44. };
  45. enum server_task_type {
  46. SERVER_TASK_TYPE_INFERENCE,
  47. SERVER_TASK_TYPE_CANCEL,
  48. SERVER_TASK_TYPE_NEXT_RESPONSE,
  49. SERVER_TASK_TYPE_METRICS,
  50. SERVER_TASK_TYPE_SLOT_SAVE,
  51. SERVER_TASK_TYPE_SLOT_RESTORE,
  52. SERVER_TASK_TYPE_SLOT_ERASE,
  53. SERVER_TASK_TYPE_SET_LORA,
  54. };
  55. enum server_task_inf_type {
  56. SERVER_TASK_INF_TYPE_COMPLETION,
  57. SERVER_TASK_INF_TYPE_EMBEDDING,
  58. SERVER_TASK_INF_TYPE_RERANK,
  59. SERVER_TASK_INF_TYPE_INFILL,
  60. };
  61. struct server_task {
  62. int id = -1; // to be filled by server_queue
  63. int id_target = -1; // used by SERVER_TASK_TYPE_CANCEL
  64. llama_tokens prompt_tokens;
  65. server_task_type type;
  66. json data;
  67. server_task_inf_type inf_type = SERVER_TASK_INF_TYPE_COMPLETION;
  68. // utility function
  69. static std::unordered_set<int> get_list_id(const std::vector<server_task> & tasks) {
  70. std::unordered_set<int> ids(tasks.size());
  71. for (size_t i = 0; i < tasks.size(); i++) {
  72. ids.insert(tasks[i].id);
  73. }
  74. return ids;
  75. }
  76. };
  77. struct server_task_result {
  78. int id = -1;
  79. json data;
  80. bool stop;
  81. bool error;
  82. };
  83. struct slot_params {
  84. bool stream = true;
  85. bool cache_prompt = true; // remember the prompt to avoid reprocessing all prompt
  86. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  87. int32_t n_discard = 0; // number of tokens after n_keep that may be discarded when shifting context, 0 defaults to half
  88. int32_t n_predict = -1; // new tokens to predict
  89. int32_t n_indent = 0; // mininum line indentation for the generated text in number of whitespace characters
  90. int64_t t_max_prompt_ms = -1; // TODO: implement
  91. int64_t t_max_predict_ms = -1; // if positive, limit the generation phase to this time limit
  92. std::vector<std::string> antiprompt;
  93. struct common_params_sampling sampling;
  94. struct common_params_speculative speculative;
  95. };
  96. struct server_slot {
  97. int id;
  98. int id_task = -1;
  99. llama_batch batch_spec;
  100. llama_context * ctx_dft = nullptr;
  101. common_speculative * spec = nullptr;
  102. // the index relative to completion multi-task request
  103. size_t index = 0;
  104. struct slot_params params;
  105. slot_state state = SLOT_STATE_IDLE;
  106. // used to determine the slot that has been used the longest
  107. int64_t t_last_used = -1;
  108. // generation props
  109. int32_t n_ctx = 0; // context size per slot
  110. int32_t n_past = 0;
  111. int32_t n_decoded = 0;
  112. int32_t n_remaining = -1;
  113. int32_t i_batch = -1;
  114. int32_t n_predict = -1; // TODO: disambiguate from params.n_predict
  115. // n_prompt_tokens may not be equal to prompt_tokens.size(), because prompt maybe truncated
  116. int32_t n_prompt_tokens = 0;
  117. int32_t n_prompt_tokens_processed = 0;
  118. // input prompt tokens
  119. llama_tokens prompt_tokens;
  120. size_t last_nl_pos = 0;
  121. std::string generated_text;
  122. llama_tokens cache_tokens;
  123. std::vector<completion_token_output> generated_token_probs;
  124. server_task_inf_type inf_type = SERVER_TASK_INF_TYPE_COMPLETION;
  125. bool has_next_token = true;
  126. bool has_new_line = false;
  127. bool truncated = false;
  128. bool stopped_eos = false;
  129. bool stopped_word = false;
  130. bool stopped_limit = false;
  131. bool timings_per_token = false;
  132. bool oaicompat = false;
  133. std::string oaicompat_model;
  134. std::string stopping_word;
  135. // sampling
  136. json json_schema;
  137. struct common_sampler * smpl = nullptr;
  138. llama_token sampled;
  139. // stats
  140. size_t n_sent_text = 0; // number of sent text character
  141. size_t n_sent_token_probs = 0;
  142. int64_t t_start_process_prompt;
  143. int64_t t_start_generation;
  144. double t_prompt_processing; // ms
  145. double t_token_generation; // ms
  146. std::function<void(int)> callback_on_release;
  147. void reset() {
  148. SLT_DBG(*this, "%s", "\n");
  149. n_prompt_tokens = 0;
  150. last_nl_pos = 0;
  151. generated_text = "";
  152. has_new_line = false;
  153. truncated = false;
  154. stopped_eos = false;
  155. stopped_word = false;
  156. stopped_limit = false;
  157. stopping_word = "";
  158. n_past = 0;
  159. n_sent_text = 0;
  160. n_sent_token_probs = 0;
  161. inf_type = SERVER_TASK_INF_TYPE_COMPLETION;
  162. generated_token_probs.clear();
  163. }
  164. bool has_budget(const common_params & global_params) {
  165. if (params.n_predict == -1 && global_params.n_predict == -1) {
  166. return true; // limitless
  167. }
  168. n_remaining = -1;
  169. if (params.n_predict != -1) {
  170. n_remaining = params.n_predict - n_decoded;
  171. } else if (global_params.n_predict != -1) {
  172. n_remaining = global_params.n_predict - n_decoded;
  173. }
  174. return n_remaining > 0; // no budget
  175. }
  176. bool is_processing() const {
  177. return state != SLOT_STATE_IDLE;
  178. }
  179. bool can_speculate() const {
  180. return ctx_dft && params.speculative.n_max > 0 && params.cache_prompt;
  181. }
  182. void add_token(const completion_token_output & token) {
  183. if (!is_processing()) {
  184. SLT_WRN(*this, "%s", "slot is not processing\n");
  185. return;
  186. }
  187. generated_token_probs.push_back(token);
  188. }
  189. void release() {
  190. if (is_processing()) {
  191. SLT_INF(*this, "stop processing: n_past = %d, truncated = %d\n", n_past, truncated);
  192. t_last_used = ggml_time_us();
  193. t_token_generation = (ggml_time_us() - t_start_generation) / 1e3;
  194. state = SLOT_STATE_IDLE;
  195. callback_on_release(id);
  196. }
  197. }
  198. json get_formated_timings() const {
  199. return json {
  200. {"prompt_n", n_prompt_tokens_processed},
  201. {"prompt_ms", t_prompt_processing},
  202. {"prompt_per_token_ms", t_prompt_processing / n_prompt_tokens_processed},
  203. {"prompt_per_second", 1e3 / t_prompt_processing * n_prompt_tokens_processed},
  204. {"predicted_n", n_decoded},
  205. {"predicted_ms", t_token_generation},
  206. {"predicted_per_token_ms", t_token_generation / n_decoded},
  207. {"predicted_per_second", 1e3 / t_token_generation * n_decoded},
  208. };
  209. }
  210. size_t find_stopping_strings(const std::string & text, const size_t last_token_size, const stop_type type) {
  211. size_t stop_pos = std::string::npos;
  212. for (const std::string & word : params.antiprompt) {
  213. size_t pos;
  214. if (type == STOP_TYPE_FULL) {
  215. const size_t tmp = word.size() + last_token_size;
  216. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  217. pos = text.find(word, from_pos);
  218. } else {
  219. pos = find_partial_stop_string(word, text);
  220. }
  221. if (pos != std::string::npos && (stop_pos == std::string::npos || pos < stop_pos)) {
  222. if (type == STOP_TYPE_FULL) {
  223. stopped_word = true;
  224. stopping_word = word;
  225. has_next_token = false;
  226. }
  227. stop_pos = pos;
  228. }
  229. }
  230. return stop_pos;
  231. }
  232. void print_timings() const {
  233. const double t_prompt = t_prompt_processing / n_prompt_tokens_processed;
  234. const double n_prompt_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  235. const double t_gen = t_token_generation / n_decoded;
  236. const double n_gen_second = 1e3 / t_token_generation * n_decoded;
  237. SLT_INF(*this,
  238. "\n"
  239. "\rprompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n"
  240. "\r eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n"
  241. "\r total time = %10.2f ms / %5d tokens\n",
  242. t_prompt_processing, n_prompt_tokens_processed, t_prompt, n_prompt_second,
  243. t_token_generation, n_decoded, t_gen, n_gen_second,
  244. t_prompt_processing + t_token_generation, n_prompt_tokens_processed + n_decoded);
  245. }
  246. };
  247. struct server_metrics {
  248. int64_t t_start = 0;
  249. uint64_t n_prompt_tokens_processed_total = 0;
  250. uint64_t t_prompt_processing_total = 0;
  251. uint64_t n_tokens_predicted_total = 0;
  252. uint64_t t_tokens_generation_total = 0;
  253. uint64_t n_prompt_tokens_processed = 0;
  254. uint64_t t_prompt_processing = 0;
  255. uint64_t n_tokens_predicted = 0;
  256. uint64_t t_tokens_generation = 0;
  257. uint64_t n_decode_total = 0;
  258. uint64_t n_busy_slots_total = 0;
  259. void init() {
  260. t_start = ggml_time_us();
  261. }
  262. void on_prompt_eval(const server_slot & slot) {
  263. n_prompt_tokens_processed_total += slot.n_prompt_tokens_processed;
  264. n_prompt_tokens_processed += slot.n_prompt_tokens_processed;
  265. t_prompt_processing += slot.t_prompt_processing;
  266. t_prompt_processing_total += slot.t_prompt_processing;
  267. }
  268. void on_prediction(const server_slot & slot) {
  269. n_tokens_predicted_total += slot.n_decoded;
  270. n_tokens_predicted += slot.n_decoded;
  271. t_tokens_generation += slot.t_token_generation;
  272. t_tokens_generation_total += slot.t_token_generation;
  273. }
  274. void on_decoded(const std::vector<server_slot> & slots) {
  275. n_decode_total++;
  276. for (const auto & slot : slots) {
  277. if (slot.is_processing()) {
  278. n_busy_slots_total++;
  279. }
  280. }
  281. }
  282. void reset_bucket() {
  283. n_prompt_tokens_processed = 0;
  284. t_prompt_processing = 0;
  285. n_tokens_predicted = 0;
  286. t_tokens_generation = 0;
  287. }
  288. };
  289. struct server_queue {
  290. int id = 0;
  291. bool running;
  292. // queues
  293. std::deque<server_task> queue_tasks;
  294. std::deque<server_task> queue_tasks_deferred;
  295. std::mutex mutex_tasks;
  296. std::condition_variable condition_tasks;
  297. // callback functions
  298. std::function<void(server_task)> callback_new_task;
  299. std::function<void(void)> callback_update_slots;
  300. // Add a new task to the end of the queue
  301. int post(server_task task, bool front = false) {
  302. std::unique_lock<std::mutex> lock(mutex_tasks);
  303. if (task.id == -1) {
  304. task.id = id++;
  305. }
  306. QUE_DBG("new task, id = %d, front = %d\n", task.id, front);
  307. if (front) {
  308. queue_tasks.push_front(std::move(task));
  309. } else {
  310. queue_tasks.push_back(std::move(task));
  311. }
  312. condition_tasks.notify_one();
  313. return task.id;
  314. }
  315. // multi-task version of post()
  316. int post(std::vector<server_task> & tasks, bool front = false) {
  317. std::unique_lock<std::mutex> lock(mutex_tasks);
  318. for (auto & task : tasks) {
  319. if (task.id == -1) {
  320. task.id = id++;
  321. }
  322. QUE_DBG("new task, id = %d/%d, front = %d\n", task.id, (int) tasks.size(), front);
  323. if (front) {
  324. queue_tasks.push_front(std::move(task));
  325. } else {
  326. queue_tasks.push_back(std::move(task));
  327. }
  328. }
  329. condition_tasks.notify_one();
  330. return 0;
  331. }
  332. // Add a new task, but defer until one slot is available
  333. void defer(server_task task) {
  334. std::unique_lock<std::mutex> lock(mutex_tasks);
  335. QUE_DBG("defer task, id = %d\n", task.id);
  336. queue_tasks_deferred.push_back(std::move(task));
  337. condition_tasks.notify_one();
  338. }
  339. // Get the next id for creating a new task
  340. int get_new_id() {
  341. std::unique_lock<std::mutex> lock(mutex_tasks);
  342. int new_id = id++;
  343. return new_id;
  344. }
  345. // Register function to process a new task
  346. void on_new_task(std::function<void(server_task)> callback) {
  347. callback_new_task = std::move(callback);
  348. }
  349. // Register the function to be called when all slots data is ready to be processed
  350. void on_update_slots(std::function<void(void)> callback) {
  351. callback_update_slots = std::move(callback);
  352. }
  353. // Call when the state of one slot is changed, it will move one task from deferred to main queue
  354. void pop_deferred_task() {
  355. std::unique_lock<std::mutex> lock(mutex_tasks);
  356. if (!queue_tasks_deferred.empty()) {
  357. queue_tasks.emplace_back(std::move(queue_tasks_deferred.front()));
  358. queue_tasks_deferred.pop_front();
  359. }
  360. condition_tasks.notify_one();
  361. }
  362. // end the start_loop routine
  363. void terminate() {
  364. std::unique_lock<std::mutex> lock(mutex_tasks);
  365. running = false;
  366. condition_tasks.notify_all();
  367. }
  368. /**
  369. * Main loop consists of these steps:
  370. * - Wait until a new task arrives
  371. * - Process the task (i.e. maybe copy data into slot)
  372. * - Check if multitask is finished
  373. * - Update all slots
  374. */
  375. void start_loop() {
  376. running = true;
  377. while (true) {
  378. QUE_DBG("%s", "processing new tasks\n");
  379. while (true) {
  380. std::unique_lock<std::mutex> lock(mutex_tasks);
  381. if (queue_tasks.empty()) {
  382. lock.unlock();
  383. break;
  384. }
  385. server_task task = queue_tasks.front();
  386. queue_tasks.pop_front();
  387. lock.unlock();
  388. QUE_DBG("processing task, id = %d\n", task.id);
  389. callback_new_task(std::move(task));
  390. }
  391. // all tasks in the current loop is processed, slots data is now ready
  392. QUE_DBG("%s", "update slots\n");
  393. callback_update_slots();
  394. QUE_DBG("%s", "waiting for new tasks\n");
  395. {
  396. std::unique_lock<std::mutex> lock(mutex_tasks);
  397. if (queue_tasks.empty()) {
  398. if (!running) {
  399. QUE_DBG("%s", "terminate\n");
  400. return;
  401. }
  402. condition_tasks.wait(lock, [&]{
  403. return (!queue_tasks.empty() || !running);
  404. });
  405. }
  406. }
  407. }
  408. }
  409. };
  410. struct server_response {
  411. // for keeping track of all tasks waiting for the result
  412. std::unordered_set<int> waiting_task_ids;
  413. // the main result queue
  414. std::vector<server_task_result> queue_results;
  415. std::mutex mutex_results;
  416. std::condition_variable condition_results;
  417. // add the id_task to the list of tasks waiting for response
  418. void add_waiting_task_id(int id_task) {
  419. SRV_DBG("add task %d to waiting list. current waiting = %d (before add)\n", id_task, (int) waiting_task_ids.size());
  420. std::unique_lock<std::mutex> lock(mutex_results);
  421. waiting_task_ids.insert(id_task);
  422. }
  423. void add_waiting_tasks(const std::vector<server_task> & tasks) {
  424. std::unique_lock<std::mutex> lock(mutex_results);
  425. for (const auto & task : tasks) {
  426. SRV_DBG("add task %d to waiting list. current waiting = %d (before add)\n", task.id, (int) waiting_task_ids.size());
  427. waiting_task_ids.insert(task.id);
  428. }
  429. }
  430. // when the request is finished, we can remove task associated with it
  431. void remove_waiting_task_id(int id_task) {
  432. SRV_DBG("remove task %d from waiting list. current waiting = %d (before remove)\n", id_task, (int) waiting_task_ids.size());
  433. std::unique_lock<std::mutex> lock(mutex_results);
  434. waiting_task_ids.erase(id_task);
  435. }
  436. void remove_waiting_task_ids(const std::unordered_set<int> & id_tasks) {
  437. std::unique_lock<std::mutex> lock(mutex_results);
  438. for (const auto & id_task : id_tasks) {
  439. SRV_DBG("remove task %d from waiting list. current waiting = %d (before remove)\n", id_task, (int) waiting_task_ids.size());
  440. waiting_task_ids.erase(id_task);
  441. }
  442. }
  443. // This function blocks the thread until there is a response for one of the id_tasks
  444. server_task_result recv(const std::unordered_set<int> & id_tasks) {
  445. while (true) {
  446. std::unique_lock<std::mutex> lock(mutex_results);
  447. condition_results.wait(lock, [&]{
  448. return !queue_results.empty();
  449. });
  450. for (int i = 0; i < (int) queue_results.size(); i++) {
  451. if (id_tasks.find(queue_results[i].id) != id_tasks.end()) {
  452. server_task_result res = queue_results[i];
  453. queue_results.erase(queue_results.begin() + i);
  454. return res;
  455. }
  456. }
  457. }
  458. // should never reach here
  459. }
  460. // single-task version of recv()
  461. server_task_result recv(int id_task) {
  462. std::unordered_set<int> id_tasks = {id_task};
  463. return recv(id_tasks);
  464. }
  465. // Send a new result to a waiting id_task
  466. void send(server_task_result & result) {
  467. SRV_DBG("sending result for task id = %d\n", result.id);
  468. std::unique_lock<std::mutex> lock(mutex_results);
  469. for (const auto & id_task : waiting_task_ids) {
  470. if (result.id == id_task) {
  471. SRV_DBG("task id = %d moved to result queue\n", result.id);
  472. queue_results.push_back(std::move(result));
  473. condition_results.notify_all();
  474. return;
  475. }
  476. }
  477. }
  478. };
  479. struct server_context {
  480. common_params params_base;
  481. llama_model * model = nullptr;
  482. llama_context * ctx = nullptr;
  483. std::vector<common_lora_adapter_container> loras;
  484. llama_model * model_dft = nullptr;
  485. llama_context_params cparams_dft;
  486. llama_batch batch = {};
  487. bool clean_kv_cache = true;
  488. bool add_bos_token = true;
  489. bool has_eos_token = false;
  490. int32_t n_ctx; // total context for all clients / slots
  491. // slots / clients
  492. std::vector<server_slot> slots;
  493. json default_generation_settings_for_props;
  494. server_queue queue_tasks;
  495. server_response queue_results;
  496. server_metrics metrics;
  497. // Necessary similarity of prompt for slot selection
  498. float slot_prompt_similarity = 0.0f;
  499. ~server_context() {
  500. if (ctx) {
  501. llama_free(ctx);
  502. ctx = nullptr;
  503. }
  504. if (model) {
  505. llama_free_model(model);
  506. model = nullptr;
  507. }
  508. if (model_dft) {
  509. llama_free_model(model_dft);
  510. model_dft = nullptr;
  511. }
  512. // Clear any sampling context
  513. for (server_slot & slot : slots) {
  514. common_sampler_free(slot.smpl);
  515. slot.smpl = nullptr;
  516. llama_free(slot.ctx_dft);
  517. slot.ctx_dft = nullptr;
  518. common_speculative_free(slot.spec);
  519. slot.spec = nullptr;
  520. llama_batch_free(slot.batch_spec);
  521. }
  522. llama_batch_free(batch);
  523. }
  524. bool load_model(const common_params & params) {
  525. SRV_INF("loading model '%s'\n", params.model.c_str());
  526. params_base = params;
  527. common_init_result llama_init = common_init_from_params(params_base);
  528. model = llama_init.model;
  529. ctx = llama_init.context;
  530. loras = llama_init.lora_adapters;
  531. if (model == nullptr) {
  532. SRV_ERR("failed to load model, '%s'\n", params_base.model.c_str());
  533. return false;
  534. }
  535. n_ctx = llama_n_ctx(ctx);
  536. add_bos_token = llama_add_bos_token(model);
  537. has_eos_token = !llama_add_eos_token(model);
  538. if (!params_base.speculative.model.empty()) {
  539. SRV_INF("loading draft model '%s'\n", params_base.speculative.model.c_str());
  540. auto params_dft = params_base;
  541. params_dft.devices = params_base.speculative.devices;
  542. params_dft.model = params_base.speculative.model;
  543. params_dft.n_ctx = params_base.speculative.n_ctx == 0 ? params_base.n_ctx / params_base.n_parallel : params_base.speculative.n_ctx;
  544. params_dft.n_gpu_layers = params_base.speculative.n_gpu_layers;
  545. params_dft.n_parallel = 1;
  546. common_init_result llama_init_dft = common_init_from_params(params_dft);
  547. model_dft = llama_init_dft.model;
  548. if (model_dft == nullptr) {
  549. SRV_ERR("failed to load draft model, '%s'\n", params_base.speculative.model.c_str());
  550. return false;
  551. }
  552. if (!common_speculative_are_compatible(ctx, llama_init_dft.context)) {
  553. SRV_ERR("the draft model '%s' is not compatible with the target model '%s'\n", params_base.speculative.model.c_str(), params_base.model.c_str());
  554. llama_free (llama_init_dft.context);
  555. llama_free_model(llama_init_dft.model);
  556. return false;
  557. }
  558. const int n_ctx_dft = llama_n_ctx(llama_init_dft.context);
  559. cparams_dft = common_context_params_to_llama(params_dft);
  560. cparams_dft.n_batch = n_ctx_dft;
  561. // force F16 KV cache for the draft model for extra performance
  562. cparams_dft.type_k = GGML_TYPE_F16;
  563. cparams_dft.type_v = GGML_TYPE_F16;
  564. // the context is not needed - we will create one for each slot
  565. llama_free(llama_init_dft.context);
  566. }
  567. return true;
  568. }
  569. bool validate_model_chat_template() const {
  570. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  571. std::string template_key = "tokenizer.chat_template";
  572. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  573. if (res >= 0) {
  574. llama_chat_message chat[] = {{"user", "test"}};
  575. std::string tmpl = std::string(model_template.data(), model_template.size());
  576. int32_t chat_res = llama_chat_apply_template(model, tmpl.c_str(), chat, 1, true, nullptr, 0);
  577. return chat_res > 0;
  578. }
  579. return false;
  580. }
  581. void init() {
  582. const int32_t n_ctx_slot = n_ctx / params_base.n_parallel;
  583. SRV_INF("initializing slots, n_slots = %d\n", params_base.n_parallel);
  584. for (int i = 0; i < params_base.n_parallel; i++) {
  585. server_slot slot;
  586. slot.id = i;
  587. slot.n_ctx = n_ctx_slot;
  588. slot.n_predict = params_base.n_predict;
  589. if (model_dft) {
  590. slot.batch_spec = llama_batch_init(params_base.speculative.n_max + 1, 0, 1);
  591. slot.ctx_dft = llama_new_context_with_model(model_dft, cparams_dft);
  592. if (slot.ctx_dft == nullptr) {
  593. SRV_ERR("%s", "failed to create draft context\n");
  594. return;
  595. }
  596. slot.spec = common_speculative_init(slot.ctx_dft);
  597. if (slot.spec == nullptr) {
  598. SRV_ERR("%s", "failed to create speculator\n");
  599. return;
  600. }
  601. }
  602. SLT_INF(slot, "new slot n_ctx_slot = %d\n", slot.n_ctx);
  603. slot.params.sampling = params_base.sampling;
  604. slot.callback_on_release = [this](int) {
  605. queue_tasks.pop_deferred_task();
  606. };
  607. slot.reset();
  608. slots.push_back(slot);
  609. }
  610. default_generation_settings_for_props = get_formated_generation(slots.front());
  611. default_generation_settings_for_props["seed"] = -1;
  612. // the update_slots() logic will always submit a maximum of n_batch or n_parallel tokens
  613. // 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)
  614. {
  615. const int32_t n_batch = llama_n_batch(ctx);
  616. // only a single seq_id per token is needed
  617. batch = llama_batch_init(std::max(n_batch, params_base.n_parallel), 0, 1);
  618. }
  619. metrics.init();
  620. }
  621. server_slot * get_slot_by_id(int id) {
  622. for (server_slot & slot : slots) {
  623. if (slot.id == id) {
  624. return &slot;
  625. }
  626. }
  627. return nullptr;
  628. }
  629. server_slot * get_available_slot(const server_task & task) {
  630. server_slot * ret = nullptr;
  631. // find the slot that has at least n% prompt similarity
  632. if (ret == nullptr && slot_prompt_similarity != 0.0f) {
  633. int lcs_len = 0;
  634. float similarity = 0;
  635. for (server_slot & slot : slots) {
  636. // skip the slot if it is not available
  637. if (slot.is_processing()) {
  638. continue;
  639. }
  640. // skip the slot if it does not contains cached tokens
  641. if (slot.cache_tokens.empty()) {
  642. continue;
  643. }
  644. // length of the Longest Common Subsequence between the current slot's prompt and the input prompt
  645. int cur_lcs_len = common_lcs(slot.cache_tokens, task.prompt_tokens);
  646. // fraction of the common subsequence length compared to the current slot's prompt length
  647. float cur_similarity = static_cast<float>(cur_lcs_len) / static_cast<int>(slot.cache_tokens.size());
  648. // select the current slot if the criteria match
  649. if (cur_lcs_len > lcs_len && cur_similarity > slot_prompt_similarity) {
  650. lcs_len = cur_lcs_len;
  651. similarity = cur_similarity;
  652. ret = &slot;
  653. }
  654. }
  655. if (ret != nullptr) {
  656. SLT_DBG(*ret, "selected slot by lcs similarity, lcs_len = %d, similarity = %f\n", lcs_len, similarity);
  657. }
  658. }
  659. // find the slot that has been least recently used
  660. if (ret == nullptr) {
  661. int64_t t_last = ggml_time_us();
  662. for (server_slot & slot : slots) {
  663. // skip the slot if it is not available
  664. if (slot.is_processing()) {
  665. continue;
  666. }
  667. // select the current slot if the criteria match
  668. if (slot.t_last_used < t_last) {
  669. t_last = slot.t_last_used;
  670. ret = &slot;
  671. }
  672. }
  673. if (ret != nullptr) {
  674. SLT_DBG(*ret, "selected slot by lru, t_last = %" PRId64 "\n", t_last);
  675. }
  676. }
  677. return ret;
  678. }
  679. bool launch_slot_with_task(server_slot & slot, const server_task & task) {
  680. // Sampling parameter defaults are loaded from the global server context (but individual requests can still override them)
  681. slot_params defaults;
  682. defaults.sampling = params_base.sampling;
  683. defaults.speculative = params_base.speculative;
  684. const auto & data = task.data;
  685. if (data.count("__oaicompat") != 0) {
  686. slot.oaicompat = true;
  687. slot.oaicompat_model = json_value(data, "model", std::string(DEFAULT_OAICOMPAT_MODEL));
  688. } else {
  689. slot.oaicompat = false;
  690. slot.oaicompat_model = "";
  691. }
  692. slot.timings_per_token = json_value(data, "timings_per_token", false);
  693. slot.params.stream = json_value(data, "stream", false);
  694. slot.params.cache_prompt = json_value(data, "cache_prompt", true);
  695. slot.params.n_predict = json_value(data, "n_predict", json_value(data, "max_tokens", defaults.n_predict));
  696. slot.params.n_indent = json_value(data, "n_indent", defaults.n_indent);
  697. slot.params.n_keep = json_value(data, "n_keep", defaults.n_keep);
  698. slot.params.n_discard = json_value(data, "n_discard", defaults.n_discard);
  699. //slot.params.t_max_prompt_ms = json_value(data, "t_max_prompt_ms", defaults.t_max_prompt_ms); // TODO: implement
  700. slot.params.t_max_predict_ms = json_value(data, "t_max_predict_ms", defaults.t_max_predict_ms);
  701. slot.params.sampling.top_k = json_value(data, "top_k", defaults.sampling.top_k);
  702. slot.params.sampling.top_p = json_value(data, "top_p", defaults.sampling.top_p);
  703. slot.params.sampling.min_p = json_value(data, "min_p", defaults.sampling.min_p);
  704. slot.params.sampling.xtc_probability = json_value(data, "xtc_probability", defaults.sampling.xtc_probability);
  705. slot.params.sampling.xtc_threshold = json_value(data, "xtc_threshold", defaults.sampling.xtc_threshold);
  706. slot.params.sampling.typ_p = json_value(data, "typical_p", defaults.sampling.typ_p);
  707. slot.params.sampling.temp = json_value(data, "temperature", defaults.sampling.temp);
  708. slot.params.sampling.dynatemp_range = json_value(data, "dynatemp_range", defaults.sampling.dynatemp_range);
  709. slot.params.sampling.dynatemp_exponent = json_value(data, "dynatemp_exponent", defaults.sampling.dynatemp_exponent);
  710. slot.params.sampling.penalty_last_n = json_value(data, "repeat_last_n", defaults.sampling.penalty_last_n);
  711. slot.params.sampling.penalty_repeat = json_value(data, "repeat_penalty", defaults.sampling.penalty_repeat);
  712. slot.params.sampling.penalty_freq = json_value(data, "frequency_penalty", defaults.sampling.penalty_freq);
  713. slot.params.sampling.penalty_present = json_value(data, "presence_penalty", defaults.sampling.penalty_present);
  714. slot.params.sampling.dry_multiplier = json_value(data, "dry_multiplier", defaults.sampling.dry_multiplier);
  715. slot.params.sampling.dry_base = json_value(data, "dry_base", defaults.sampling.dry_base);
  716. slot.params.sampling.dry_allowed_length = json_value(data, "dry_allowed_length", defaults.sampling.dry_allowed_length);
  717. slot.params.sampling.dry_penalty_last_n = json_value(data, "dry_penalty_last_n", defaults.sampling.dry_penalty_last_n);
  718. slot.params.sampling.mirostat = json_value(data, "mirostat", defaults.sampling.mirostat);
  719. slot.params.sampling.mirostat_tau = json_value(data, "mirostat_tau", defaults.sampling.mirostat_tau);
  720. slot.params.sampling.mirostat_eta = json_value(data, "mirostat_eta", defaults.sampling.mirostat_eta);
  721. slot.params.sampling.penalize_nl = json_value(data, "penalize_nl", defaults.sampling.penalize_nl);
  722. slot.params.sampling.seed = json_value(data, "seed", defaults.sampling.seed);
  723. slot.params.sampling.n_probs = json_value(data, "n_probs", defaults.sampling.n_probs);
  724. slot.params.sampling.min_keep = json_value(data, "min_keep", defaults.sampling.min_keep);
  725. slot.params.speculative.n_min = json_value(data, "speculative.n_min", defaults.speculative.n_min);
  726. slot.params.speculative.n_max = json_value(data, "speculative.n_max", defaults.speculative.n_max);
  727. slot.params.speculative.p_min = json_value(data, "speculative.p_min", defaults.speculative.p_min);
  728. slot.params.speculative.n_min = std::min(slot.params.speculative.n_max, slot.params.speculative.n_min);
  729. slot.params.speculative.n_min = std::max(slot.params.speculative.n_min, 2);
  730. slot.params.speculative.n_max = std::max(slot.params.speculative.n_max, 0);
  731. if (slot.params.sampling.dry_base < 1.0f) {
  732. slot.params.sampling.dry_base = defaults.sampling.dry_base;
  733. }
  734. // sequence breakers for DRY
  735. {
  736. // Currently, this is not compatible with TextGen WebUI, Koboldcpp and SillyTavern format
  737. // Ref: https://github.com/oobabooga/text-generation-webui/blob/d1af7a41ade7bd3c3a463bfa640725edb818ebaf/extensions/openai/typing.py#L39
  738. if (data.contains("dry_sequence_breakers")) {
  739. slot.params.sampling.dry_sequence_breakers = json_value(data, "dry_sequence_breakers", std::vector<std::string>());
  740. if (slot.params.sampling.dry_sequence_breakers.empty()) {
  741. send_error(task, "Error: dry_sequence_breakers must be a non-empty array of strings", ERROR_TYPE_INVALID_REQUEST);
  742. return false;
  743. }
  744. }
  745. }
  746. // process "json_schema" and "grammar"
  747. if (data.contains("json_schema") && !data.at("json_schema").is_null() && data.contains("grammar") && !data.at("grammar").is_null()) {
  748. send_error(task, "Either \"json_schema\" or \"grammar\" can be specified, but not both", ERROR_TYPE_INVALID_REQUEST);
  749. return false;
  750. }
  751. if (data.contains("json_schema") && !data.contains("grammar")) {
  752. try {
  753. auto schema = json_value(data, "json_schema", json::object());
  754. slot.params.sampling.grammar = json_schema_to_grammar(schema);
  755. } catch (const std::exception & e) {
  756. send_error(task, std::string("\"json_schema\": ") + e.what(), ERROR_TYPE_INVALID_REQUEST);
  757. return false;
  758. }
  759. } else {
  760. slot.params.sampling.grammar = json_value(data, "grammar", defaults.sampling.grammar);
  761. }
  762. if (slot.n_predict > 0 && slot.params.n_predict > slot.n_predict) {
  763. // Might be better to reject the request with a 400 ?
  764. slot.params.n_predict = slot.n_predict;
  765. SLT_WRN(slot, "n_predict = %d exceeds server configuration, setting to %d", slot.n_predict, slot.n_predict);
  766. }
  767. {
  768. slot.params.sampling.logit_bias.clear();
  769. if (json_value(data, "ignore_eos", false) && has_eos_token) {
  770. slot.params.sampling.logit_bias.push_back({llama_token_eos(model), -INFINITY});
  771. }
  772. const auto & logit_bias = data.find("logit_bias");
  773. if (logit_bias != data.end() && logit_bias->is_array()) {
  774. const int n_vocab = llama_n_vocab(model);
  775. for (const auto & el : *logit_bias) {
  776. // TODO: we may want to throw errors here, in case "el" is incorrect
  777. if (el.is_array() && el.size() == 2) {
  778. float bias;
  779. if (el[1].is_number()) {
  780. bias = el[1].get<float>();
  781. } else if (el[1].is_boolean() && !el[1].get<bool>()) {
  782. bias = -INFINITY;
  783. } else {
  784. continue;
  785. }
  786. if (el[0].is_number_integer()) {
  787. llama_token tok = el[0].get<llama_token>();
  788. if (tok >= 0 && tok < n_vocab) {
  789. slot.params.sampling.logit_bias.push_back({tok, bias});
  790. }
  791. } else if (el[0].is_string()) {
  792. auto toks = common_tokenize(model, el[0].get<std::string>(), false);
  793. for (auto tok : toks) {
  794. slot.params.sampling.logit_bias.push_back({tok, bias});
  795. }
  796. }
  797. }
  798. }
  799. }
  800. }
  801. {
  802. slot.params.antiprompt.clear();
  803. const auto & stop = data.find("stop");
  804. if (stop != data.end() && stop->is_array()) {
  805. for (const auto & word : *stop) {
  806. if (!word.empty()) {
  807. slot.params.antiprompt.push_back(word);
  808. }
  809. }
  810. }
  811. }
  812. {
  813. const auto & samplers = data.find("samplers");
  814. if (samplers != data.end()) {
  815. if (samplers->is_array()) {
  816. std::vector<std::string> sampler_names;
  817. for (const auto & name : *samplers) {
  818. if (name.is_string()) {
  819. sampler_names.emplace_back(name);
  820. }
  821. }
  822. slot.params.sampling.samplers = common_sampler_types_from_names(sampler_names, false);
  823. } else if (samplers->is_string()){
  824. std::string sampler_string;
  825. for (const auto & name : *samplers) {
  826. sampler_string += name;
  827. }
  828. slot.params.sampling.samplers = common_sampler_types_from_chars(sampler_string);
  829. }
  830. } else {
  831. slot.params.sampling.samplers = defaults.sampling.samplers;
  832. }
  833. }
  834. {
  835. if (slot.smpl != nullptr) {
  836. common_sampler_free(slot.smpl);
  837. }
  838. slot.smpl = common_sampler_init(model, slot.params.sampling);
  839. if (slot.smpl == nullptr) {
  840. // for now, the only error that may happen here is invalid grammar
  841. send_error(task, "Failed to parse grammar", ERROR_TYPE_INVALID_REQUEST);
  842. return false;
  843. }
  844. }
  845. if (slot.ctx_dft) {
  846. llama_batch_free(slot.batch_spec);
  847. slot.batch_spec = llama_batch_init(slot.params.speculative.n_max + 1, 0, 1);
  848. }
  849. slot.state = SLOT_STATE_STARTED;
  850. SLT_INF(slot, "%s", "processing task\n");
  851. return true;
  852. }
  853. void kv_cache_clear() {
  854. SRV_DBG("%s", "clearing KV cache\n");
  855. // clear the entire KV cache
  856. llama_kv_cache_clear(ctx);
  857. clean_kv_cache = false;
  858. }
  859. bool process_token(completion_token_output & result, server_slot & slot) {
  860. // remember which tokens were sampled - used for repetition penalties during sampling
  861. const std::string token_str = common_token_to_piece(ctx, result.tok, params_base.special);
  862. slot.sampled = result.tok;
  863. // search stop word and delete it
  864. slot.generated_text += token_str;
  865. slot.has_next_token = true;
  866. // check if there is incomplete UTF-8 character at the end
  867. bool incomplete = false;
  868. for (unsigned i = 1; i < 5 && i <= slot.generated_text.size(); ++i) {
  869. unsigned char c = slot.generated_text[slot.generated_text.size() - i];
  870. if ((c & 0xC0) == 0x80) {
  871. // continuation byte: 10xxxxxx
  872. continue;
  873. }
  874. if ((c & 0xE0) == 0xC0) {
  875. // 2-byte character: 110xxxxx ...
  876. incomplete = i < 2;
  877. } else if ((c & 0xF0) == 0xE0) {
  878. // 3-byte character: 1110xxxx ...
  879. incomplete = i < 3;
  880. } else if ((c & 0xF8) == 0xF0) {
  881. // 4-byte character: 11110xxx ...
  882. incomplete = i < 4;
  883. }
  884. // else 1-byte character or invalid byte
  885. break;
  886. }
  887. if (!incomplete) {
  888. size_t pos = std::min(slot.n_sent_text, slot.generated_text.size());
  889. const std::string str_test = slot.generated_text.substr(pos);
  890. bool send_text = true;
  891. size_t stop_pos = slot.find_stopping_strings(str_test, token_str.size(), STOP_TYPE_FULL);
  892. if (stop_pos != std::string::npos) {
  893. slot.generated_text.erase(
  894. slot.generated_text.begin() + pos + stop_pos,
  895. slot.generated_text.end());
  896. pos = std::min(slot.n_sent_text, slot.generated_text.size());
  897. } else if (slot.has_next_token) {
  898. stop_pos = slot.find_stopping_strings(str_test, token_str.size(), STOP_TYPE_PARTIAL);
  899. send_text = stop_pos == std::string::npos;
  900. }
  901. // check if there is any token to predict
  902. if (send_text) {
  903. // no send the stop word in the response
  904. result.text_to_send = slot.generated_text.substr(pos, std::string::npos);
  905. slot.n_sent_text += result.text_to_send.size();
  906. // add the token to slot queue and cache
  907. }
  908. slot.add_token(result);
  909. if (slot.params.stream) {
  910. send_partial_response(slot, result);
  911. }
  912. }
  913. if (incomplete) {
  914. slot.has_next_token = true;
  915. }
  916. // check the limits
  917. if (slot.n_decoded > 0 && slot.has_next_token && !slot.has_budget(params_base)) {
  918. slot.stopped_limit = true;
  919. slot.has_next_token = false;
  920. SLT_DBG(slot, "stopped by limit, n_decoded = %d, n_predict = %d\n", slot.n_decoded, slot.params.n_predict);
  921. }
  922. if (slot.has_new_line) {
  923. // if we have already seen a new line, we stop after a certain time limit
  924. if (slot.params.t_max_predict_ms > 0 && (ggml_time_us() - slot.t_start_generation > 1000.0f*slot.params.t_max_predict_ms)) {
  925. slot.stopped_limit = true;
  926. slot.has_next_token = false;
  927. SLT_DBG(slot, "stopped by time limit, n_decoded = %d, t_max_predict_ms = %d ms\n", slot.n_decoded, (int) slot.params.t_max_predict_ms);
  928. }
  929. // require that each new line has a whitespace prefix (i.e. indentation) of at least slot.params.n_indent
  930. if (slot.params.n_indent > 0) {
  931. // check the current indentation
  932. // TODO: improve by not doing it more than once for each new line
  933. if (slot.last_nl_pos > 0) {
  934. size_t pos = slot.last_nl_pos;
  935. int n_indent = 0;
  936. while (pos < slot.generated_text.size() && (slot.generated_text[pos] == ' ' || slot.generated_text[pos] == '\t')) {
  937. n_indent++;
  938. pos++;
  939. }
  940. if (pos < slot.generated_text.size() && n_indent < slot.params.n_indent) {
  941. slot.stopped_limit = true;
  942. slot.has_next_token = false;
  943. // cut the last line
  944. slot.generated_text.erase(pos, std::string::npos);
  945. SLT_DBG(slot, "stopped by indentation limit, n_decoded = %d, n_indent = %d\n", slot.n_decoded, n_indent);
  946. }
  947. }
  948. // find the next new line
  949. {
  950. const size_t pos = slot.generated_text.find('\n', slot.last_nl_pos);
  951. if (pos != std::string::npos) {
  952. slot.last_nl_pos = pos + 1;
  953. }
  954. }
  955. }
  956. }
  957. // check if there is a new line in the generated text
  958. if (result.text_to_send.find('\n') != std::string::npos) {
  959. slot.has_new_line = true;
  960. }
  961. // if context shift is disabled, we stop when it reaches the context limit
  962. if (slot.n_past >= slot.n_ctx) {
  963. slot.truncated = true;
  964. slot.stopped_limit = true;
  965. slot.has_next_token = false;
  966. SLT_DBG(slot, "stopped due to running out of context capacity, n_past = %d, n_prompt_tokens = %d, n_decoded = %d, n_ctx = %d\n",
  967. slot.n_decoded, slot.n_prompt_tokens, slot.n_past, slot.n_ctx);
  968. }
  969. if (llama_token_is_eog(model, result.tok)) {
  970. slot.stopped_eos = true;
  971. slot.has_next_token = false;
  972. SLT_DBG(slot, "%s", "stopped by EOS\n");
  973. }
  974. const auto n_ctx_train = llama_n_ctx_train(model);
  975. if (slot.params.n_predict < 1 && slot.n_predict < 1 && slot.n_prompt_tokens + slot.n_decoded >= n_ctx_train) {
  976. slot.truncated = true;
  977. slot.stopped_limit = true;
  978. slot.has_next_token = false; // stop prediction
  979. SLT_WRN(slot,
  980. "n_predict (%d) is set for infinite generation. "
  981. "Limiting generated tokens to n_ctx_train (%d) to avoid EOS-less generation infinite loop\n",
  982. slot.params.n_predict, n_ctx_train);
  983. }
  984. 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());
  985. return slot.has_next_token; // continue
  986. }
  987. json get_formated_generation(const server_slot & slot) const {
  988. std::vector<std::string> samplers;
  989. samplers.reserve(slot.params.sampling.samplers.size());
  990. for (const auto & sampler : slot.params.sampling.samplers) {
  991. samplers.emplace_back(common_sampler_type_to_str(sampler));
  992. }
  993. return json {
  994. {"n_ctx", slot.n_ctx},
  995. {"n_predict", slot.n_predict}, // Server configured n_predict
  996. {"model", params_base.model_alias},
  997. {"seed", slot.params.sampling.seed},
  998. {"seed_cur", slot.smpl ? common_sampler_get_seed(slot.smpl) : 0},
  999. {"temperature", slot.params.sampling.temp},
  1000. {"dynatemp_range", slot.params.sampling.dynatemp_range},
  1001. {"dynatemp_exponent", slot.params.sampling.dynatemp_exponent},
  1002. {"top_k", slot.params.sampling.top_k},
  1003. {"top_p", slot.params.sampling.top_p},
  1004. {"min_p", slot.params.sampling.min_p},
  1005. {"xtc_probability", slot.params.sampling.xtc_probability},
  1006. {"xtc_threshold", slot.params.sampling.xtc_threshold},
  1007. {"typical_p", slot.params.sampling.typ_p},
  1008. {"repeat_last_n", slot.params.sampling.penalty_last_n},
  1009. {"repeat_penalty", slot.params.sampling.penalty_repeat},
  1010. {"presence_penalty", slot.params.sampling.penalty_present},
  1011. {"frequency_penalty", slot.params.sampling.penalty_freq},
  1012. {"dry_multiplier", slot.params.sampling.dry_multiplier},
  1013. {"dry_base", slot.params.sampling.dry_base},
  1014. {"dry_allowed_length", slot.params.sampling.dry_allowed_length},
  1015. {"dry_penalty_last_n", slot.params.sampling.dry_penalty_last_n},
  1016. {"dry_sequence_breakers", slot.params.sampling.dry_sequence_breakers},
  1017. {"mirostat", slot.params.sampling.mirostat},
  1018. {"mirostat_tau", slot.params.sampling.mirostat_tau},
  1019. {"mirostat_eta", slot.params.sampling.mirostat_eta},
  1020. {"penalize_nl", slot.params.sampling.penalize_nl},
  1021. {"stop", slot.params.antiprompt},
  1022. {"max_tokens", slot.params.n_predict}, // User configured n_predict
  1023. {"n_keep", slot.params.n_keep},
  1024. {"n_discard", slot.params.n_discard},
  1025. {"ignore_eos", slot.params.sampling.ignore_eos},
  1026. {"stream", slot.params.stream},
  1027. //{"logit_bias", slot.params.sampling.logit_bias},
  1028. {"n_probs", slot.params.sampling.n_probs},
  1029. {"min_keep", slot.params.sampling.min_keep},
  1030. {"grammar", slot.params.sampling.grammar},
  1031. {"samplers", samplers},
  1032. {"speculative", slot.can_speculate()},
  1033. {"speculative.n_max", slot.params.speculative.n_max},
  1034. {"speculative.n_min", slot.params.speculative.n_min},
  1035. {"speculative.p_min", slot.params.speculative.p_min},
  1036. {"timings_per_token", slot.timings_per_token},
  1037. };
  1038. }
  1039. void send_error(const server_task & task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1040. send_error(task.id, error, type);
  1041. }
  1042. void send_error(const server_slot & slot, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1043. send_error(slot.id_task, error, type);
  1044. }
  1045. void send_error(const int id_task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1046. SRV_ERR("task id = %d, error: %s\n", id_task, error.c_str());
  1047. server_task_result res;
  1048. res.id = id_task;
  1049. res.stop = false;
  1050. res.error = true;
  1051. res.data = format_error_response(error, type);
  1052. queue_results.send(res);
  1053. }
  1054. void send_partial_response(server_slot & slot, completion_token_output tkn) {
  1055. server_task_result res;
  1056. res.id = slot.id_task;
  1057. res.error = false;
  1058. res.stop = false;
  1059. res.data = json {
  1060. {"content", tkn.text_to_send},
  1061. {"stop", false},
  1062. {"id_slot", slot.id},
  1063. {"multimodal", false},
  1064. {"index", slot.index},
  1065. };
  1066. if (slot.params.sampling.n_probs > 0) {
  1067. const llama_tokens to_send_toks = common_tokenize(ctx, tkn.text_to_send, false);
  1068. const size_t probs_pos = std::min(slot.n_sent_token_probs, slot.generated_token_probs.size());
  1069. const size_t probs_stop_pos = std::min(slot.n_sent_token_probs + to_send_toks.size(), slot.generated_token_probs.size());
  1070. std::vector<completion_token_output> probs_output;
  1071. if (probs_pos < probs_stop_pos) {
  1072. probs_output = std::vector<completion_token_output>(
  1073. slot.generated_token_probs.begin() + probs_pos,
  1074. slot.generated_token_probs.begin() + probs_stop_pos);
  1075. }
  1076. slot.n_sent_token_probs = probs_stop_pos;
  1077. res.data["completion_probabilities"] = probs_vector_to_json(ctx, probs_output);
  1078. }
  1079. if (slot.oaicompat) {
  1080. res.data["oaicompat_token_ctr"] = slot.n_decoded;
  1081. res.data["model"] = slot.oaicompat_model;
  1082. }
  1083. if (slot.timings_per_token) {
  1084. res.data["timings"] = slot.get_formated_timings();
  1085. }
  1086. queue_results.send(res);
  1087. }
  1088. void send_final_response(const server_slot & slot) {
  1089. server_task_result res;
  1090. res.id = slot.id_task;
  1091. res.error = false;
  1092. res.stop = true;
  1093. res.data = json {
  1094. {"content", !slot.params.stream ? slot.generated_text : ""},
  1095. {"id_slot", slot.id},
  1096. {"stop", true},
  1097. {"model", params_base.model_alias},
  1098. {"tokens_predicted", slot.n_decoded},
  1099. {"tokens_evaluated", slot.n_prompt_tokens},
  1100. {"generation_settings", get_formated_generation(slot)},
  1101. {"prompt", common_detokenize(ctx, slot.prompt_tokens)},
  1102. {"has_new_line", slot.has_new_line},
  1103. {"truncated", slot.truncated},
  1104. {"stopped_eos", slot.stopped_eos},
  1105. {"stopped_word", slot.stopped_word},
  1106. {"stopped_limit", slot.stopped_limit},
  1107. {"stopping_word", slot.stopping_word},
  1108. {"tokens_cached", slot.n_past},
  1109. {"timings", slot.get_formated_timings()},
  1110. {"index", slot.index},
  1111. };
  1112. if (slot.params.sampling.n_probs > 0) {
  1113. std::vector<completion_token_output> probs;
  1114. if (!slot.params.stream && slot.stopped_word) {
  1115. const llama_tokens stop_word_toks = common_tokenize(ctx, slot.stopping_word, false);
  1116. size_t safe_offset = std::min(slot.generated_token_probs.size(), stop_word_toks.size());
  1117. probs = std::vector<completion_token_output>(
  1118. slot.generated_token_probs.begin(),
  1119. slot.generated_token_probs.end() - safe_offset);
  1120. } else {
  1121. probs = std::vector<completion_token_output>(
  1122. slot.generated_token_probs.begin(),
  1123. slot.generated_token_probs.end());
  1124. }
  1125. res.data["completion_probabilities"] = probs_vector_to_json(ctx, probs);
  1126. }
  1127. if (slot.oaicompat) {
  1128. res.data["oaicompat_token_ctr"] = slot.n_decoded;
  1129. res.data["model"] = slot.oaicompat_model;
  1130. }
  1131. queue_results.send(res);
  1132. }
  1133. void send_embedding(const server_slot & slot, const llama_batch & batch) {
  1134. server_task_result res;
  1135. res.id = slot.id_task;
  1136. res.error = false;
  1137. res.stop = true;
  1138. const int n_embd = llama_n_embd(model);
  1139. std::vector<float> embd_res(n_embd, 0.0f);
  1140. for (int i = 0; i < batch.n_tokens; ++i) {
  1141. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  1142. continue;
  1143. }
  1144. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1145. if (embd == NULL) {
  1146. embd = llama_get_embeddings_ith(ctx, i);
  1147. }
  1148. if (embd == NULL) {
  1149. SLT_ERR(slot, "failed to get embeddings, token = %d, seq_id = %d\n", batch.token[i], batch.seq_id[i][0]);
  1150. res.data = json {
  1151. {"embedding", std::vector<float>(n_embd, 0.0f)},
  1152. {"index", slot.index},
  1153. };
  1154. continue;
  1155. }
  1156. common_embd_normalize(embd, embd_res.data(), n_embd);
  1157. res.data = json {
  1158. {"embedding", embd_res},
  1159. {"index", slot.index},
  1160. };
  1161. }
  1162. SLT_DBG(slot, "%s", "sending embeddings\n");
  1163. queue_results.send(res);
  1164. }
  1165. void send_rerank(const server_slot & slot, const llama_batch & batch) {
  1166. server_task_result res;
  1167. res.id = slot.id_task;
  1168. res.error = false;
  1169. res.stop = true;
  1170. for (int i = 0; i < batch.n_tokens; ++i) {
  1171. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  1172. continue;
  1173. }
  1174. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1175. if (embd == NULL) {
  1176. embd = llama_get_embeddings_ith(ctx, i);
  1177. }
  1178. if (embd == NULL) {
  1179. SLT_ERR(slot, "failed to get embeddings, token = %d, seq_id = %d\n", batch.token[i], batch.seq_id[i][0]);
  1180. res.data = json {
  1181. {"index", slot.index},
  1182. {"score", -1e6},
  1183. };
  1184. continue;
  1185. }
  1186. res.data = json {
  1187. {"index", slot.index},
  1188. {"score", embd[0]},
  1189. };
  1190. }
  1191. SLT_DBG(slot, "sending rerank result, res = '%s'\n", res.data.dump().c_str());
  1192. queue_results.send(res);
  1193. }
  1194. //
  1195. // Functions to create new task(s) and receive result(s)
  1196. //
  1197. // break the input "prompt" into multiple tasks if needed, then format and tokenize the input prompt(s)
  1198. std::vector<server_task> create_tasks_inference(json data, server_task_inf_type inf_type) {
  1199. std::vector<server_task> tasks;
  1200. auto create_task = [&](json & task_data, llama_tokens & prompt_tokens) {
  1201. SRV_DBG("create task, n_tokens = %d\n", (int) prompt_tokens.size());
  1202. server_task task;
  1203. task.id = queue_tasks.get_new_id();
  1204. task.inf_type = inf_type;
  1205. task.type = SERVER_TASK_TYPE_INFERENCE;
  1206. task.data = task_data;
  1207. task.prompt_tokens = std::move(prompt_tokens);
  1208. tasks.push_back(std::move(task));
  1209. };
  1210. static constexpr const char * error_msg = "\"prompt\" must be a string, an array of token ids or an array of prompts";
  1211. if (!data.contains("prompt")) {
  1212. throw std::runtime_error(error_msg);
  1213. }
  1214. // because llama_tokenize api is thread-safe, we can tokenize the prompt from HTTP thread
  1215. bool add_special = inf_type != SERVER_TASK_INF_TYPE_RERANK && inf_type != SERVER_TASK_INF_TYPE_INFILL;
  1216. std::vector<llama_tokens> tokenized_prompts = tokenize_input_prompts(ctx, data.at("prompt"), add_special, true);
  1217. switch (inf_type) {
  1218. case SERVER_TASK_INF_TYPE_RERANK:
  1219. {
  1220. // prompts[0] is the question
  1221. // the rest are the answers/documents
  1222. GGML_ASSERT(tokenized_prompts.size() > 1);
  1223. SRV_DBG("creating rerank tasks, n_prompts = %d\n", (int) tokenized_prompts.size() - 1);
  1224. for (size_t i = 1; i < tokenized_prompts.size(); i++) {
  1225. data["index"] = i - 1;
  1226. auto tokens = format_rerank(model, tokenized_prompts[0], tokenized_prompts[i]);
  1227. create_task(data, tokens);
  1228. }
  1229. } break;
  1230. case SERVER_TASK_INF_TYPE_INFILL:
  1231. {
  1232. SRV_DBG("creating infill tasks, n_prompts = %d\n", (int) tokenized_prompts.size());
  1233. for (size_t i = 0; i < tokenized_prompts.size(); i++) {
  1234. data["index"] = i;
  1235. auto tokens = format_infill(
  1236. ctx,
  1237. data.at("input_prefix"),
  1238. data.at("input_suffix"),
  1239. data.at("input_extra"),
  1240. params_base.n_batch,
  1241. params_base.n_predict,
  1242. slots[0].n_ctx, // TODO: there should be a better way
  1243. params_base.spm_infill,
  1244. tokenized_prompts[i]
  1245. );
  1246. create_task(data, tokens);
  1247. }
  1248. } break;
  1249. default:
  1250. {
  1251. SRV_DBG("creating multi-prompt tasks, n_prompts = %d\n", (int) tokenized_prompts.size());
  1252. for (size_t i = 0; i < tokenized_prompts.size(); i++) {
  1253. data["index"] = i;
  1254. create_task(data, tokenized_prompts[i]);
  1255. }
  1256. }
  1257. }
  1258. return tasks;
  1259. }
  1260. void cancel_tasks(const std::unordered_set<int> & id_tasks) {
  1261. std::vector<server_task> cancel_tasks;
  1262. cancel_tasks.reserve(id_tasks.size());
  1263. for (const auto & id_task : id_tasks) {
  1264. SRV_WRN("cancel task, id_task = %d\n", id_task);
  1265. server_task task;
  1266. task.type = SERVER_TASK_TYPE_CANCEL;
  1267. task.id_target = id_task;
  1268. cancel_tasks.push_back(task);
  1269. queue_results.remove_waiting_task_id(id_task);
  1270. }
  1271. // push to beginning of the queue, so it has highest priority
  1272. queue_tasks.post(cancel_tasks, true);
  1273. }
  1274. // receive the results from task(s) created by create_tasks_inference
  1275. void receive_cmpl_results(
  1276. const std::unordered_set<int> & id_tasks,
  1277. const std::function<void(std::vector<server_task_result>&)> & result_handler,
  1278. const std::function<void(json)> & error_handler) {
  1279. // TODO: currently, there is no way to detect the client has cancelled the request
  1280. std::vector<server_task_result> results(id_tasks.size());
  1281. for (size_t i = 0; i < id_tasks.size(); i++) {
  1282. server_task_result result = queue_results.recv(id_tasks);
  1283. if (result.error) {
  1284. error_handler(result.data);
  1285. cancel_tasks(id_tasks);
  1286. return;
  1287. }
  1288. const size_t idx = result.data["index"];
  1289. GGML_ASSERT(idx < results.size() && "index out of range");
  1290. results[idx] = result;
  1291. }
  1292. result_handler(results);
  1293. }
  1294. // receive the results from task(s) created by create_tasks_inference, in stream mode
  1295. void receive_cmpl_results_stream(
  1296. const std::unordered_set<int> & id_tasks, const
  1297. std::function<bool(server_task_result&)> & result_handler, const
  1298. std::function<void(json)> & error_handler) {
  1299. size_t n_finished = 0;
  1300. while (true) {
  1301. server_task_result result = queue_results.recv(id_tasks);
  1302. if (!result_handler(result)) {
  1303. cancel_tasks(id_tasks);
  1304. break;
  1305. }
  1306. if (result.error) {
  1307. error_handler(result.data);
  1308. cancel_tasks(id_tasks);
  1309. break;
  1310. }
  1311. if (result.stop) {
  1312. if (++n_finished == id_tasks.size()) {
  1313. break;
  1314. }
  1315. }
  1316. }
  1317. }
  1318. //
  1319. // Functions to process the task
  1320. //
  1321. void process_single_task(server_task task) {
  1322. switch (task.type) {
  1323. case SERVER_TASK_TYPE_INFERENCE:
  1324. {
  1325. const int id_slot = json_value(task.data, "id_slot", -1);
  1326. server_slot * slot = id_slot != -1 ? get_slot_by_id(id_slot) : get_available_slot(task);
  1327. if (slot == nullptr) {
  1328. // if no slot is available, we defer this task for processing later
  1329. SRV_DBG("no slot is available, defer task, id_task = %d\n", task.id);
  1330. queue_tasks.defer(task);
  1331. break;
  1332. }
  1333. if (slot->is_processing()) {
  1334. // if requested slot is unavailable, we defer this task for processing later
  1335. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1336. queue_tasks.defer(task);
  1337. break;
  1338. }
  1339. slot->reset();
  1340. slot->id_task = task.id;
  1341. slot->inf_type = task.inf_type;
  1342. slot->index = json_value(task.data, "index", 0);
  1343. slot->prompt_tokens = std::move(task.prompt_tokens);
  1344. if (!launch_slot_with_task(*slot, task)) {
  1345. SRV_ERR("failed to launch slot with task, id_task = %d\n", task.id);
  1346. break;
  1347. }
  1348. } break;
  1349. case SERVER_TASK_TYPE_CANCEL:
  1350. {
  1351. // release slot linked with the task id
  1352. for (auto & slot : slots) {
  1353. if (slot.id_task == task.id_target) {
  1354. slot.release();
  1355. break;
  1356. }
  1357. }
  1358. } break;
  1359. case SERVER_TASK_TYPE_NEXT_RESPONSE:
  1360. {
  1361. // do nothing
  1362. } break;
  1363. case SERVER_TASK_TYPE_METRICS:
  1364. {
  1365. json slots_data = json::array();
  1366. int n_idle_slots = 0;
  1367. int n_processing_slots = 0;
  1368. for (server_slot & slot : slots) {
  1369. json slot_data = get_formated_generation(slot);
  1370. slot_data["id"] = slot.id;
  1371. slot_data["id_task"] = slot.id_task;
  1372. slot_data["is_processing"] = slot.is_processing();
  1373. slot_data["prompt"] = common_detokenize(ctx, slot.prompt_tokens);
  1374. slot_data["next_token"] = {
  1375. {"has_next_token", slot.has_next_token},
  1376. {"has_new_line", slot.has_new_line},
  1377. {"n_remain", slot.n_remaining},
  1378. {"n_decoded", slot.n_decoded},
  1379. {"stopped_eos", slot.stopped_eos},
  1380. {"stopped_word", slot.stopped_word},
  1381. {"stopped_limit", slot.stopped_limit},
  1382. {"stopping_word", slot.stopping_word},
  1383. };
  1384. if (slot.is_processing()) {
  1385. n_processing_slots++;
  1386. } else {
  1387. n_idle_slots++;
  1388. }
  1389. slots_data.push_back(slot_data);
  1390. }
  1391. SRV_DBG("n_idle_slots = %d, n_processing_slots = %d\n", n_idle_slots, n_processing_slots);
  1392. server_task_result res;
  1393. res.id = task.id;
  1394. res.stop = true;
  1395. res.error = false;
  1396. res.data = {
  1397. { "idle", n_idle_slots },
  1398. { "processing", n_processing_slots },
  1399. { "deferred", queue_tasks.queue_tasks_deferred.size() },
  1400. { "t_start", metrics.t_start},
  1401. { "n_prompt_tokens_processed_total", metrics.n_prompt_tokens_processed_total},
  1402. { "t_tokens_generation_total", metrics.t_tokens_generation_total},
  1403. { "n_tokens_predicted_total", metrics.n_tokens_predicted_total},
  1404. { "t_prompt_processing_total", metrics.t_prompt_processing_total},
  1405. { "n_prompt_tokens_processed", metrics.n_prompt_tokens_processed},
  1406. { "t_prompt_processing", metrics.t_prompt_processing},
  1407. { "n_tokens_predicted", metrics.n_tokens_predicted},
  1408. { "t_tokens_generation", metrics.t_tokens_generation},
  1409. { "n_decode_total", metrics.n_decode_total},
  1410. { "n_busy_slots_total", metrics.n_busy_slots_total},
  1411. { "kv_cache_tokens_count", llama_get_kv_cache_token_count(ctx)},
  1412. { "kv_cache_used_cells", llama_get_kv_cache_used_cells(ctx)},
  1413. { "slots", slots_data },
  1414. };
  1415. if (json_value(task.data, "reset_bucket", false)) {
  1416. metrics.reset_bucket();
  1417. }
  1418. queue_results.send(res);
  1419. } break;
  1420. case SERVER_TASK_TYPE_SLOT_SAVE:
  1421. {
  1422. int id_slot = task.data.at("id_slot");
  1423. server_slot * slot = get_slot_by_id(id_slot);
  1424. if (slot == nullptr) {
  1425. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1426. break;
  1427. }
  1428. if (slot->is_processing()) {
  1429. // if requested slot is unavailable, we defer this task for processing later
  1430. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1431. queue_tasks.defer(task);
  1432. break;
  1433. }
  1434. const size_t token_count = slot->cache_tokens.size();
  1435. const int64_t t_start = ggml_time_us();
  1436. std::string filename = task.data.at("filename");
  1437. std::string filepath = task.data.at("filepath");
  1438. const size_t nwrite = llama_state_seq_save_file(ctx, filepath.c_str(), slot->id, slot->cache_tokens.data(), token_count);
  1439. const int64_t t_end = ggml_time_us();
  1440. const double t_save_ms = (t_end - t_start) / 1000.0;
  1441. server_task_result result;
  1442. result.id = task.id;
  1443. result.stop = true;
  1444. result.error = false;
  1445. result.data = json {
  1446. { "id_slot", id_slot },
  1447. { "filename", filename },
  1448. { "n_saved", token_count }, // tokens saved
  1449. { "n_written", nwrite }, // bytes written
  1450. { "timings", {
  1451. { "save_ms", t_save_ms }
  1452. } }
  1453. };
  1454. queue_results.send(result);
  1455. } break;
  1456. case SERVER_TASK_TYPE_SLOT_RESTORE:
  1457. {
  1458. int id_slot = task.data.at("id_slot");
  1459. server_slot * slot = get_slot_by_id(id_slot);
  1460. if (slot == nullptr) {
  1461. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1462. break;
  1463. }
  1464. if (slot->is_processing()) {
  1465. // if requested slot is unavailable, we defer this task for processing later
  1466. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1467. queue_tasks.defer(task);
  1468. break;
  1469. }
  1470. const int64_t t_start = ggml_time_us();
  1471. std::string filename = task.data.at("filename");
  1472. std::string filepath = task.data.at("filepath");
  1473. slot->cache_tokens.resize(slot->n_ctx);
  1474. size_t token_count = 0;
  1475. size_t nread = llama_state_seq_load_file(ctx, filepath.c_str(), slot->id, slot->cache_tokens.data(), slot->cache_tokens.size(), &token_count);
  1476. if (nread == 0) {
  1477. slot->cache_tokens.resize(0);
  1478. send_error(task, "Unable to restore slot, no available space in KV cache or invalid slot save file", ERROR_TYPE_INVALID_REQUEST);
  1479. break;
  1480. }
  1481. slot->cache_tokens.resize(token_count);
  1482. const int64_t t_end = ggml_time_us();
  1483. const double t_restore_ms = (t_end - t_start) / 1000.0;
  1484. server_task_result result;
  1485. result.id = task.id;
  1486. result.stop = true;
  1487. result.error = false;
  1488. result.data = json {
  1489. { "id_slot", id_slot },
  1490. { "filename", filename },
  1491. { "n_restored", token_count }, // tokens restored
  1492. { "n_read", nread }, // bytes read
  1493. { "timings", {
  1494. { "restore_ms", t_restore_ms }
  1495. } }
  1496. };
  1497. queue_results.send(result);
  1498. } break;
  1499. case SERVER_TASK_TYPE_SLOT_ERASE:
  1500. {
  1501. int id_slot = task.data.at("id_slot");
  1502. server_slot * slot = get_slot_by_id(id_slot);
  1503. if (slot == nullptr) {
  1504. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1505. break;
  1506. }
  1507. if (slot->is_processing()) {
  1508. // if requested slot is unavailable, we defer this task for processing later
  1509. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1510. queue_tasks.defer(task);
  1511. break;
  1512. }
  1513. // Erase token cache
  1514. const size_t n_erased = slot->cache_tokens.size();
  1515. llama_kv_cache_seq_rm(ctx, slot->id, -1, -1);
  1516. slot->cache_tokens.clear();
  1517. server_task_result result;
  1518. result.id = task.id;
  1519. result.stop = true;
  1520. result.error = false;
  1521. result.data = json {
  1522. { "id_slot", id_slot },
  1523. { "n_erased", n_erased }
  1524. };
  1525. queue_results.send(result);
  1526. } break;
  1527. case SERVER_TASK_TYPE_SET_LORA:
  1528. {
  1529. common_lora_adapters_apply(ctx, loras);
  1530. server_task_result result;
  1531. result.id = task.id;
  1532. result.stop = true;
  1533. result.error = false;
  1534. result.data = json{{ "success", true }};
  1535. queue_results.send(result);
  1536. } break;
  1537. }
  1538. }
  1539. void update_slots() {
  1540. // check if all slots are idle
  1541. {
  1542. bool all_idle = true;
  1543. for (auto & slot : slots) {
  1544. if (slot.is_processing()) {
  1545. all_idle = false;
  1546. break;
  1547. }
  1548. }
  1549. if (all_idle) {
  1550. SRV_INF("%s", "all slots are idle\n");
  1551. if (clean_kv_cache) {
  1552. kv_cache_clear();
  1553. }
  1554. return;
  1555. }
  1556. }
  1557. {
  1558. SRV_DBG("%s", "posting NEXT_RESPONSE\n");
  1559. server_task task;
  1560. task.type = SERVER_TASK_TYPE_NEXT_RESPONSE;
  1561. task.id_target = -1;
  1562. queue_tasks.post(task);
  1563. }
  1564. // apply context-shift if needed
  1565. // TODO: simplify and improve
  1566. for (server_slot & slot : slots) {
  1567. if (slot.is_processing() && slot.n_past + 1 >= slot.n_ctx) {
  1568. if (!params_base.ctx_shift) {
  1569. // this check is redundant (for good)
  1570. // we should never get here, because generation should already stopped in process_token()
  1571. slot.release();
  1572. send_error(slot, "context shift is disabled", ERROR_TYPE_SERVER);
  1573. continue;
  1574. }
  1575. // Shift context
  1576. const int n_keep = slot.params.n_keep + add_bos_token;
  1577. const int n_left = slot.n_past - n_keep;
  1578. const int n_discard = slot.params.n_discard ? slot.params.n_discard : (n_left / 2);
  1579. SLT_WRN(slot, "slot context shift, n_keep = %d, n_left = %d, n_discard = %d\n", n_keep, n_left, n_discard);
  1580. llama_kv_cache_seq_rm (ctx, slot.id, n_keep , n_keep + n_discard);
  1581. llama_kv_cache_seq_add(ctx, slot.id, n_keep + n_discard, slot.n_past, -n_discard);
  1582. if (slot.params.cache_prompt) {
  1583. for (size_t i = n_keep + n_discard; i < slot.cache_tokens.size(); i++) {
  1584. slot.cache_tokens[i - n_discard] = slot.cache_tokens[i];
  1585. }
  1586. slot.cache_tokens.resize(slot.cache_tokens.size() - n_discard);
  1587. }
  1588. slot.n_past -= n_discard;
  1589. slot.truncated = true;
  1590. }
  1591. }
  1592. // start populating the batch for this iteration
  1593. common_batch_clear(batch);
  1594. // frist, add sampled tokens from any ongoing sequences
  1595. for (auto & slot : slots) {
  1596. if (slot.state != SLOT_STATE_GENERATING) {
  1597. continue;
  1598. }
  1599. slot.i_batch = batch.n_tokens;
  1600. common_batch_add(batch, slot.sampled, slot.n_past, { slot.id }, true);
  1601. slot.n_past += 1;
  1602. if (slot.params.cache_prompt) {
  1603. slot.cache_tokens.push_back(slot.sampled);
  1604. }
  1605. SLT_DBG(slot, "slot decode token, n_ctx = %d, n_past = %d, n_cache_tokens = %d, truncated = %d\n",
  1606. slot.n_ctx, slot.n_past, (int) slot.cache_tokens.size(), slot.truncated);
  1607. }
  1608. // process in chunks of params.n_batch
  1609. int32_t n_batch = llama_n_batch(ctx);
  1610. int32_t n_ubatch = llama_n_ubatch(ctx);
  1611. // track if this is an embedding or non-embedding batch
  1612. // if we've added sampled tokens above, we are in non-embedding mode
  1613. // -1: none, 0: non-embedding, 1: embedding
  1614. // TODO: make enum
  1615. int32_t batch_type = batch.n_tokens > 0 ? 0 : -1;
  1616. // next, batch any pending prompts without exceeding n_batch
  1617. if (params_base.cont_batching || batch.n_tokens == 0) {
  1618. for (auto & slot : slots) {
  1619. // this slot still has a prompt to be processed
  1620. if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_STARTED) {
  1621. auto & prompt_tokens = slot.prompt_tokens;
  1622. // TODO: maybe move branch to outside of this loop in the future
  1623. if (slot.state == SLOT_STATE_STARTED) {
  1624. slot.t_start_process_prompt = ggml_time_us();
  1625. slot.t_start_generation = 0;
  1626. slot.n_past = 0;
  1627. slot.n_prompt_tokens = prompt_tokens.size();
  1628. slot.state = SLOT_STATE_PROCESSING_PROMPT;
  1629. SLT_INF(slot, "new prompt, n_ctx_slot = %d, n_keep = %d, n_prompt_tokens = %d\n", slot.n_ctx, slot.params.n_keep, slot.n_prompt_tokens);
  1630. // print prompt tokens (for debugging)
  1631. if (1) {
  1632. // first 16 tokens (avoid flooding logs)
  1633. for (int i = 0; i < std::min<int>(16, prompt_tokens.size()); i++) {
  1634. SLT_DBG(slot, "prompt token %3d: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  1635. }
  1636. } else {
  1637. // all
  1638. for (int i = 0; i < (int) prompt_tokens.size(); i++) {
  1639. SLT_DBG(slot, "prompt token %3d: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  1640. }
  1641. }
  1642. // empty prompt passed -> release the slot and send empty response
  1643. if (prompt_tokens.empty()) {
  1644. SLT_WRN(slot, "%s", "empty prompt - releasing slot\n");
  1645. slot.release();
  1646. slot.print_timings();
  1647. send_final_response(slot);
  1648. continue;
  1649. }
  1650. if (slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING || slot.inf_type == SERVER_TASK_INF_TYPE_RERANK) {
  1651. if (slot.n_prompt_tokens > n_ubatch) {
  1652. slot.release();
  1653. send_error(slot, "input is too large to process. increase the physical batch size", ERROR_TYPE_SERVER);
  1654. continue;
  1655. }
  1656. if (slot.n_prompt_tokens > slot.n_ctx) {
  1657. slot.release();
  1658. send_error(slot, "input is larger than the max context size. skipping", ERROR_TYPE_SERVER);
  1659. continue;
  1660. }
  1661. } else {
  1662. if (!params_base.ctx_shift) {
  1663. // if context shift is disabled, we make sure prompt size is smaller than KV size
  1664. // TODO: there should be a separate parameter that control prompt truncation
  1665. // context shift should be applied only during the generation phase
  1666. if (slot.n_prompt_tokens >= slot.n_ctx) {
  1667. slot.release();
  1668. send_error(slot, "the request exceeds the available context size. try increasing the context size or enable context shift", ERROR_TYPE_INVALID_REQUEST);
  1669. continue;
  1670. }
  1671. }
  1672. if (slot.params.n_keep < 0) {
  1673. slot.params.n_keep = slot.n_prompt_tokens;
  1674. }
  1675. slot.params.n_keep = std::min(slot.n_ctx - 4, slot.params.n_keep);
  1676. // if input prompt is too big, truncate it
  1677. if (slot.n_prompt_tokens >= slot.n_ctx) {
  1678. const int n_left = slot.n_ctx - slot.params.n_keep;
  1679. const int n_block_size = n_left / 2;
  1680. const int erased_blocks = (slot.n_prompt_tokens - slot.params.n_keep - n_block_size) / n_block_size;
  1681. llama_tokens new_tokens(
  1682. prompt_tokens.begin(),
  1683. prompt_tokens.begin() + slot.params.n_keep);
  1684. new_tokens.insert(
  1685. new_tokens.end(),
  1686. prompt_tokens.begin() + slot.params.n_keep + erased_blocks * n_block_size,
  1687. prompt_tokens.end());
  1688. prompt_tokens = std::move(new_tokens);
  1689. slot.truncated = true;
  1690. slot.n_prompt_tokens = prompt_tokens.size();
  1691. SLT_WRN(slot, "input truncated, n_ctx = %d, n_keep = %d, n_left = %d, n_prompt_tokens = %d\n", slot.n_ctx, slot.params.n_keep, n_left, slot.n_prompt_tokens);
  1692. GGML_ASSERT(slot.n_prompt_tokens < slot.n_ctx);
  1693. }
  1694. if (slot.params.cache_prompt) {
  1695. // reuse any previously computed tokens that are common with the new prompt
  1696. slot.n_past = common_lcp(slot.cache_tokens, prompt_tokens);
  1697. // reuse chunks from the cached prompt by shifting their KV cache in the new position
  1698. if (params_base.n_cache_reuse > 0) {
  1699. size_t head_c = slot.n_past; // cache
  1700. size_t head_p = slot.n_past; // current prompt
  1701. SLT_DBG(slot, "trying to reuse chunks with size > %d, slot.n_past = %d\n", params_base.n_cache_reuse, slot.n_past);
  1702. while (head_c < slot.cache_tokens.size() &&
  1703. head_p < prompt_tokens.size()) {
  1704. size_t n_match = 0;
  1705. while (head_c + n_match < slot.cache_tokens.size() &&
  1706. head_p + n_match < prompt_tokens.size() &&
  1707. slot.cache_tokens[head_c + n_match] == prompt_tokens[head_p + n_match]) {
  1708. n_match++;
  1709. }
  1710. if (n_match >= (size_t) params_base.n_cache_reuse) {
  1711. 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);
  1712. //for (size_t i = head_p; i < head_p + n_match; i++) {
  1713. // SLT_DBG(slot, "cache token %3zu: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  1714. //}
  1715. const int64_t kv_shift = (int64_t) head_p - (int64_t) head_c;
  1716. llama_kv_cache_seq_rm (ctx, slot.id, head_p, head_c);
  1717. llama_kv_cache_seq_add(ctx, slot.id, head_c, -1, kv_shift);
  1718. for (size_t i = 0; i < n_match; i++) {
  1719. slot.cache_tokens[head_p + i] = slot.cache_tokens[head_c + i];
  1720. slot.n_past++;
  1721. }
  1722. head_c += n_match;
  1723. head_p += n_match;
  1724. } else {
  1725. head_c += 1;
  1726. }
  1727. }
  1728. SLT_DBG(slot, "after context reuse, new slot.n_past = %d\n", slot.n_past);
  1729. }
  1730. }
  1731. }
  1732. if (slot.n_past == slot.n_prompt_tokens && slot.n_past > 0) {
  1733. // we have to evaluate at least 1 token to generate logits.
  1734. SLT_WRN(slot, "need to evaluate at least 1 token to generate logits, n_past = %d, n_prompt_tokens = %d\n", slot.n_past, slot.n_prompt_tokens);
  1735. slot.n_past--;
  1736. }
  1737. slot.n_prompt_tokens_processed = 0;
  1738. }
  1739. // non-causal tasks require to fit the entire prompt in the physical batch
  1740. if (slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING || slot.inf_type == SERVER_TASK_INF_TYPE_RERANK) {
  1741. // cannot fit the prompt in the current batch - will try next iter
  1742. if (batch.n_tokens + slot.n_prompt_tokens > n_batch) {
  1743. continue;
  1744. }
  1745. }
  1746. // check that we are in the right batch_type, if not defer the slot
  1747. const bool slot_type =
  1748. slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING ||
  1749. slot.inf_type == SERVER_TASK_INF_TYPE_RERANK ? 1 : 0;
  1750. if (batch_type == -1) {
  1751. batch_type = slot_type;
  1752. } else if (batch_type != slot_type) {
  1753. continue;
  1754. }
  1755. // keep only the common part
  1756. if (!llama_kv_cache_seq_rm(ctx, slot.id, slot.n_past, -1)) {
  1757. // could not partially delete (likely using a non-Transformer model)
  1758. llama_kv_cache_seq_rm(ctx, slot.id, -1, -1);
  1759. // there is no common part left
  1760. slot.n_past = 0;
  1761. }
  1762. SLT_INF(slot, "kv cache rm [%d, end)\n", slot.n_past);
  1763. // remove the non-common part from the cache
  1764. slot.cache_tokens.resize(slot.n_past);
  1765. // add prompt tokens for processing in the current batch
  1766. while (slot.n_past < slot.n_prompt_tokens && batch.n_tokens < n_batch) {
  1767. common_batch_add(batch, prompt_tokens[slot.n_past], slot.n_past, { slot.id }, false);
  1768. if (slot.params.cache_prompt) {
  1769. slot.cache_tokens.push_back(prompt_tokens[slot.n_past]);
  1770. }
  1771. slot.n_prompt_tokens_processed++;
  1772. slot.n_past++;
  1773. }
  1774. SLT_INF(slot, "prompt processing progress, n_past = %d, n_tokens = %d, progress = %f\n", slot.n_past, batch.n_tokens, (float) slot.n_prompt_tokens_processed / slot.n_prompt_tokens);
  1775. // entire prompt has been processed
  1776. if (slot.n_past == slot.n_prompt_tokens) {
  1777. slot.state = SLOT_STATE_DONE_PROMPT;
  1778. GGML_ASSERT(batch.n_tokens > 0);
  1779. common_sampler_reset(slot.smpl);
  1780. // Process all prompt tokens through sampler system
  1781. for (int i = 0; i < slot.n_prompt_tokens; ++i) {
  1782. common_sampler_accept(slot.smpl, prompt_tokens[i], false);
  1783. }
  1784. // extract the logits only for the last token
  1785. batch.logits[batch.n_tokens - 1] = true;
  1786. slot.n_decoded = 0;
  1787. slot.i_batch = batch.n_tokens - 1;
  1788. SLT_INF(slot, "prompt done, n_past = %d, n_tokens = %d\n", slot.n_past, batch.n_tokens);
  1789. }
  1790. }
  1791. if (batch.n_tokens >= n_batch) {
  1792. break;
  1793. }
  1794. }
  1795. }
  1796. if (batch.n_tokens == 0) {
  1797. SRV_WRN("%s", "no tokens to decode\n");
  1798. return;
  1799. }
  1800. SRV_DBG("decoding batch, n_tokens = %d\n", batch.n_tokens);
  1801. // make sure we're in the right embedding mode
  1802. llama_set_embeddings(ctx, batch_type == 1);
  1803. // process the created batch of tokens
  1804. for (int32_t i = 0; i < batch.n_tokens; i += n_batch) {
  1805. const int32_t n_tokens = std::min(n_batch, batch.n_tokens - i);
  1806. llama_batch batch_view = {
  1807. n_tokens,
  1808. batch.token + i,
  1809. nullptr,
  1810. batch.pos + i,
  1811. batch.n_seq_id + i,
  1812. batch.seq_id + i,
  1813. batch.logits + i,
  1814. };
  1815. const int ret = llama_decode(ctx, batch_view);
  1816. metrics.on_decoded(slots);
  1817. if (ret != 0) {
  1818. if (n_batch == 1 || ret < 0) {
  1819. // if you get here, it means the KV cache is full - try increasing it via the context size
  1820. SRV_ERR("failed to decode the batch: KV cache is full - try increasing it via the context size, i = %d, n_batch = %d, ret = %d\n", i, n_batch, ret);
  1821. for (auto & slot : slots) {
  1822. slot.release();
  1823. send_error(slot, "Input prompt is too big compared to KV size. Please try increasing KV size.");
  1824. }
  1825. break; // break loop of n_batch
  1826. }
  1827. // retry with half the batch size to try to find a free slot in the KV cache
  1828. n_batch /= 2;
  1829. i -= n_batch;
  1830. SRV_WRN("failed to find free space in the KV cache, retrying with smaller batch size - try increasing it via the context size or enable defragmentation, i = %d, n_batch = %d, ret = %d\n", i, n_batch, ret);
  1831. continue; // continue loop of n_batch
  1832. }
  1833. for (auto & slot : slots) {
  1834. if (slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens)) {
  1835. continue; // continue loop of slots
  1836. }
  1837. if (slot.state == SLOT_STATE_DONE_PROMPT) {
  1838. if (slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING) {
  1839. // prompt evaluated for embedding
  1840. send_embedding(slot, batch_view);
  1841. slot.release();
  1842. slot.i_batch = -1;
  1843. continue; // continue loop of slots
  1844. }
  1845. if (slot.inf_type == SERVER_TASK_INF_TYPE_RERANK) {
  1846. send_rerank(slot, batch_view);
  1847. slot.release();
  1848. slot.i_batch = -1;
  1849. continue; // continue loop of slots
  1850. }
  1851. // prompt evaluated for next-token prediction
  1852. slot.state = SLOT_STATE_GENERATING;
  1853. } else if (slot.state != SLOT_STATE_GENERATING) {
  1854. continue; // continue loop of slots
  1855. }
  1856. llama_token id = common_sampler_sample(slot.smpl, ctx, slot.i_batch - i);
  1857. slot.i_batch = -1;
  1858. common_sampler_accept(slot.smpl, id, true);
  1859. slot.n_decoded += 1;
  1860. const int64_t t_current = ggml_time_us();
  1861. if (slot.n_decoded == 1) {
  1862. slot.t_start_generation = t_current;
  1863. slot.t_prompt_processing = (slot.t_start_generation - slot.t_start_process_prompt) / 1e3;
  1864. metrics.on_prompt_eval(slot);
  1865. }
  1866. slot.t_token_generation = (t_current - slot.t_start_generation) / 1e3;
  1867. completion_token_output result;
  1868. result.tok = id;
  1869. const auto * cur_p = common_sampler_get_candidates(slot.smpl);
  1870. for (size_t i = 0; i < (size_t) slot.params.sampling.n_probs; ++i) {
  1871. result.probs.push_back({
  1872. cur_p->data[i].id,
  1873. i >= cur_p->size ? 0.0f : cur_p->data[i].p,
  1874. });
  1875. }
  1876. if (!process_token(result, slot)) {
  1877. // release slot because of stop condition
  1878. slot.release();
  1879. slot.print_timings();
  1880. send_final_response(slot);
  1881. metrics.on_prediction(slot);
  1882. continue;
  1883. }
  1884. }
  1885. // do speculative decoding
  1886. for (auto & slot : slots) {
  1887. if (!slot.is_processing() || !slot.can_speculate()) {
  1888. continue;
  1889. }
  1890. if (slot.state != SLOT_STATE_GENERATING) {
  1891. continue;
  1892. }
  1893. // determine the max draft that fits the current slot state
  1894. int n_draft_max = slot.params.speculative.n_max;
  1895. // note: n_past is not yet increased for the `id` token sampled above
  1896. // also, need to leave space for 1 extra token to allow context shifts
  1897. n_draft_max = std::min(n_draft_max, slot.n_ctx - slot.n_past - 2);
  1898. if (slot.n_remaining > 0) {
  1899. n_draft_max = std::min(n_draft_max, slot.n_remaining - 1);
  1900. }
  1901. SLT_DBG(slot, "max possible draft: %d\n", n_draft_max);
  1902. if (n_draft_max < slot.params.speculative.n_min) {
  1903. SLT_DBG(slot, "the max possible draft is too small: %d < %d - skipping speculative decoding\n", n_draft_max, slot.params.speculative.n_min);
  1904. continue;
  1905. }
  1906. llama_token id = slot.sampled;
  1907. struct common_speculative_params params_spec;
  1908. params_spec.n_draft = n_draft_max;
  1909. params_spec.n_reuse = llama_n_ctx(slot.ctx_dft) - slot.params.speculative.n_max;
  1910. params_spec.p_min = slot.params.speculative.p_min;
  1911. llama_tokens draft = common_speculative_gen_draft(slot.spec, params_spec, slot.cache_tokens, id);
  1912. // ignore small drafts
  1913. if (slot.params.speculative.n_min > (int) draft.size()) {
  1914. SLT_DBG(slot, "ignoring small draft: %d < %d\n", (int) draft.size(), slot.params.speculative.n_min);
  1915. continue;
  1916. }
  1917. // construct the speculation batch
  1918. common_batch_clear(slot.batch_spec);
  1919. common_batch_add (slot.batch_spec, id, slot.n_past, { slot.id }, true);
  1920. for (size_t i = 0; i < draft.size(); ++i) {
  1921. common_batch_add(slot.batch_spec, draft[i], slot.n_past + 1 + i, { slot.id }, true);
  1922. }
  1923. SLT_DBG(slot, "decoding speculative batch, size = %d\n", slot.batch_spec.n_tokens);
  1924. llama_decode(ctx, slot.batch_spec);
  1925. // the accepted tokens from the speculation
  1926. const auto ids = common_sampler_sample_and_accept_n(slot.smpl, ctx, draft);
  1927. slot.n_past += ids.size();
  1928. slot.n_decoded += ids.size();
  1929. slot.cache_tokens.push_back(id);
  1930. slot.cache_tokens.insert(slot.cache_tokens.end(), ids.begin(), ids.end() - 1);
  1931. llama_kv_cache_seq_rm(ctx, slot.id, slot.n_past, -1);
  1932. for (size_t i = 0; i < ids.size(); ++i) {
  1933. completion_token_output result;
  1934. result.tok = ids[i];
  1935. if (!process_token(result, slot)) {
  1936. // release slot because of stop condition
  1937. slot.release();
  1938. slot.print_timings();
  1939. send_final_response(slot);
  1940. metrics.on_prediction(slot);
  1941. break;
  1942. }
  1943. }
  1944. SLT_DBG(slot, "accepted %d/%d draft tokens, new n_past = %d\n", (int) ids.size() - 1, (int) draft.size(), slot.n_past);
  1945. }
  1946. }
  1947. SRV_DBG("%s", "run slots completed\n");
  1948. }
  1949. json model_meta() const {
  1950. return json {
  1951. {"vocab_type", llama_vocab_type (model)},
  1952. {"n_vocab", llama_n_vocab (model)},
  1953. {"n_ctx_train", llama_n_ctx_train (model)},
  1954. {"n_embd", llama_n_embd (model)},
  1955. {"n_params", llama_model_n_params(model)},
  1956. {"size", llama_model_size (model)},
  1957. };
  1958. }
  1959. };
  1960. static void log_server_request(const httplib::Request & req, const httplib::Response & res) {
  1961. // skip GH copilot requests when using default port
  1962. if (req.path == "/v1/health" || req.path == "/v1/completions") {
  1963. return;
  1964. }
  1965. LOG_INF("request: %s %s %s %d\n", req.method.c_str(), req.path.c_str(), req.remote_addr.c_str(), res.status);
  1966. LOG_DBG("request: %s\n", req.body.c_str());
  1967. LOG_DBG("response: %s\n", res.body.c_str());
  1968. }
  1969. std::function<void(int)> shutdown_handler;
  1970. std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
  1971. inline void signal_handler(int signal) {
  1972. if (is_terminating.test_and_set()) {
  1973. // in case it hangs, we can force terminate the server by hitting Ctrl+C twice
  1974. // this is for better developer experience, we can remove when the server is stable enough
  1975. fprintf(stderr, "Received second interrupt, terminating immediately.\n");
  1976. exit(1);
  1977. }
  1978. shutdown_handler(signal);
  1979. }
  1980. int main(int argc, char ** argv) {
  1981. // own arguments required by this example
  1982. common_params params;
  1983. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_SERVER)) {
  1984. return 1;
  1985. }
  1986. common_init();
  1987. // enabling this will output extra debug information in the HTTP responses from the server
  1988. // see format_final_response_oaicompat()
  1989. const bool verbose = params.verbosity > 9;
  1990. // struct that contains llama context and inference
  1991. server_context ctx_server;
  1992. if (params.model_alias == "unknown") {
  1993. params.model_alias = params.model;
  1994. }
  1995. llama_backend_init();
  1996. llama_numa_init(params.numa);
  1997. LOG_INF("system info: n_threads = %d, n_threads_batch = %d, total_threads = %d\n", params.cpuparams.n_threads, params.cpuparams_batch.n_threads, std::thread::hardware_concurrency());
  1998. LOG_INF("\n");
  1999. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  2000. LOG_INF("\n");
  2001. std::unique_ptr<httplib::Server> svr;
  2002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2003. if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
  2004. LOG_INF("Running with SSL: key = %s, cert = %s\n", params.ssl_file_key.c_str(), params.ssl_file_cert.c_str());
  2005. svr.reset(
  2006. new httplib::SSLServer(params.ssl_file_cert.c_str(), params.ssl_file_key.c_str())
  2007. );
  2008. } else {
  2009. LOG_INF("Running without SSL\n");
  2010. svr.reset(new httplib::Server());
  2011. }
  2012. #else
  2013. if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
  2014. LOG_ERR("Server is built without SSL support\n");
  2015. return 1;
  2016. }
  2017. svr.reset(new httplib::Server());
  2018. #endif
  2019. std::atomic<server_state> state{SERVER_STATE_LOADING_MODEL};
  2020. svr->set_default_headers({{"Server", "llama.cpp"}});
  2021. svr->set_logger(log_server_request);
  2022. auto res_error = [](httplib::Response & res, const json & error_data) {
  2023. json final_response {{"error", error_data}};
  2024. res.set_content(final_response.dump(-1, ' ', false, json::error_handler_t::replace), MIMETYPE_JSON);
  2025. res.status = json_value(error_data, "code", 500);
  2026. };
  2027. auto res_ok = [](httplib::Response & res, const json & data) {
  2028. res.set_content(data.dump(-1, ' ', false, json::error_handler_t::replace), MIMETYPE_JSON);
  2029. res.status = 200;
  2030. };
  2031. svr->set_exception_handler([&res_error](const httplib::Request &, httplib::Response & res, std::exception_ptr ep) {
  2032. std::string message;
  2033. try {
  2034. std::rethrow_exception(ep);
  2035. } catch (std::exception & e) {
  2036. message = e.what();
  2037. } catch (...) {
  2038. message = "Unknown Exception";
  2039. }
  2040. json formatted_error = format_error_response(message, ERROR_TYPE_SERVER);
  2041. LOG_WRN("got exception: %s\n", formatted_error.dump().c_str());
  2042. res_error(res, formatted_error);
  2043. });
  2044. svr->set_error_handler([&res_error](const httplib::Request &, httplib::Response & res) {
  2045. if (res.status == 404) {
  2046. res_error(res, format_error_response("File Not Found", ERROR_TYPE_NOT_FOUND));
  2047. }
  2048. // for other error codes, we skip processing here because it's already done by res_error()
  2049. });
  2050. // set timeouts and change hostname and port
  2051. svr->set_read_timeout (params.timeout_read);
  2052. svr->set_write_timeout(params.timeout_write);
  2053. std::unordered_map<std::string, std::string> log_data;
  2054. log_data["hostname"] = params.hostname;
  2055. log_data["port"] = std::to_string(params.port);
  2056. if (params.api_keys.size() == 1) {
  2057. auto key = params.api_keys[0];
  2058. log_data["api_key"] = "api_key: ****" + key.substr(std::max((int)(key.length() - 4), 0));
  2059. } else if (params.api_keys.size() > 1) {
  2060. log_data["api_key"] = "api_key: " + std::to_string(params.api_keys.size()) + " keys loaded";
  2061. }
  2062. // Necessary similarity of prompt for slot selection
  2063. ctx_server.slot_prompt_similarity = params.slot_prompt_similarity;
  2064. //
  2065. // Middlewares
  2066. //
  2067. auto middleware_validate_api_key = [&params, &res_error](const httplib::Request & req, httplib::Response & res) {
  2068. static const std::unordered_set<std::string> public_endpoints = {
  2069. "/health",
  2070. "/models",
  2071. "/v1/models",
  2072. };
  2073. // If API key is not set, skip validation
  2074. if (params.api_keys.empty()) {
  2075. return true;
  2076. }
  2077. // If path is public or is static file, skip validation
  2078. if (public_endpoints.find(req.path) != public_endpoints.end() || req.path == "/") {
  2079. return true;
  2080. }
  2081. // Check for API key in the header
  2082. auto auth_header = req.get_header_value("Authorization");
  2083. std::string prefix = "Bearer ";
  2084. if (auth_header.substr(0, prefix.size()) == prefix) {
  2085. std::string received_api_key = auth_header.substr(prefix.size());
  2086. if (std::find(params.api_keys.begin(), params.api_keys.end(), received_api_key) != params.api_keys.end()) {
  2087. return true; // API key is valid
  2088. }
  2089. }
  2090. // API key is invalid or not provided
  2091. res_error(res, format_error_response("Invalid API Key", ERROR_TYPE_AUTHENTICATION));
  2092. LOG_WRN("Unauthorized: Invalid API Key\n");
  2093. return false;
  2094. };
  2095. auto middleware_server_state = [&res_error, &state](const httplib::Request & req, httplib::Response & res) {
  2096. server_state current_state = state.load();
  2097. if (current_state == SERVER_STATE_LOADING_MODEL) {
  2098. auto tmp = string_split<std::string>(req.path, '.');
  2099. if (req.path == "/" || tmp.back() == "html") {
  2100. res.set_content(reinterpret_cast<const char*>(loading_html), loading_html_len, "text/html; charset=utf-8");
  2101. res.status = 503;
  2102. } else {
  2103. res_error(res, format_error_response("Loading model", ERROR_TYPE_UNAVAILABLE));
  2104. }
  2105. return false;
  2106. }
  2107. return true;
  2108. };
  2109. // register server middlewares
  2110. svr->set_pre_routing_handler([&middleware_validate_api_key, &middleware_server_state](const httplib::Request & req, httplib::Response & res) {
  2111. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2112. // If this is OPTIONS request, skip validation because browsers don't include Authorization header
  2113. if (req.method == "OPTIONS") {
  2114. res.set_header("Access-Control-Allow-Credentials", "true");
  2115. res.set_header("Access-Control-Allow-Methods", "GET, POST");
  2116. res.set_header("Access-Control-Allow-Headers", "*");
  2117. res.set_content("", "text/html"); // blank response, no data
  2118. return httplib::Server::HandlerResponse::Handled; // skip further processing
  2119. }
  2120. if (!middleware_server_state(req, res)) {
  2121. return httplib::Server::HandlerResponse::Handled;
  2122. }
  2123. if (!middleware_validate_api_key(req, res)) {
  2124. return httplib::Server::HandlerResponse::Handled;
  2125. }
  2126. return httplib::Server::HandlerResponse::Unhandled;
  2127. });
  2128. //
  2129. // Route handlers (or controllers)
  2130. //
  2131. const auto handle_health = [&](const httplib::Request &, httplib::Response & res) {
  2132. // error and loading states are handled by middleware
  2133. json health = {{"status", "ok"}};
  2134. res_ok(res, health);
  2135. };
  2136. const auto handle_slots = [&](const httplib::Request & req, httplib::Response & res) {
  2137. if (!params.endpoint_slots) {
  2138. res_error(res, format_error_response("This server does not support slots endpoint. Start it with `--slots`", ERROR_TYPE_NOT_SUPPORTED));
  2139. return;
  2140. }
  2141. // request slots data using task queue
  2142. server_task task;
  2143. task.id = ctx_server.queue_tasks.get_new_id();
  2144. task.type = SERVER_TASK_TYPE_METRICS;
  2145. ctx_server.queue_results.add_waiting_task_id(task.id);
  2146. ctx_server.queue_tasks.post(task, true); // high-priority task
  2147. // get the result
  2148. server_task_result result = ctx_server.queue_results.recv(task.id);
  2149. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2150. // optionally return "fail_on_no_slot" error
  2151. const int n_idle_slots = result.data.at("idle");
  2152. if (req.has_param("fail_on_no_slot")) {
  2153. if (n_idle_slots == 0) {
  2154. res_error(res, format_error_response("no slot available", ERROR_TYPE_UNAVAILABLE));
  2155. return;
  2156. }
  2157. }
  2158. res_ok(res, result.data.at("slots"));
  2159. };
  2160. const auto handle_metrics = [&](const httplib::Request &, httplib::Response & res) {
  2161. if (!params.endpoint_metrics) {
  2162. res_error(res, format_error_response("This server does not support metrics endpoint. Start it with `--metrics`", ERROR_TYPE_NOT_SUPPORTED));
  2163. return;
  2164. }
  2165. // request slots data using task queue
  2166. server_task task;
  2167. task.id = ctx_server.queue_tasks.get_new_id();
  2168. task.id_target = -1;
  2169. task.type = SERVER_TASK_TYPE_METRICS;
  2170. task.data.push_back({{"reset_bucket", true}});
  2171. ctx_server.queue_results.add_waiting_task_id(task.id);
  2172. ctx_server.queue_tasks.post(task, true); // high-priority task
  2173. // get the result
  2174. server_task_result result = ctx_server.queue_results.recv(task.id);
  2175. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2176. json data = result.data;
  2177. const uint64_t n_prompt_tokens_processed = data.at("n_prompt_tokens_processed");
  2178. const uint64_t t_prompt_processing = data.at("t_prompt_processing");
  2179. const uint64_t n_tokens_predicted = data.at("n_tokens_predicted");
  2180. const uint64_t t_tokens_generation = data.at("t_tokens_generation");
  2181. const uint64_t n_decode_total = data.at("n_decode_total");
  2182. const uint64_t n_busy_slots_total = data.at("n_busy_slots_total");
  2183. const int32_t kv_cache_used_cells = data.at("kv_cache_used_cells");
  2184. // metrics definition: https://prometheus.io/docs/practices/naming/#metric-names
  2185. json all_metrics_def = json {
  2186. {"counter", {{
  2187. {"name", "prompt_tokens_total"},
  2188. {"help", "Number of prompt tokens processed."},
  2189. {"value", (uint64_t) data.at("n_prompt_tokens_processed_total")}
  2190. }, {
  2191. {"name", "prompt_seconds_total"},
  2192. {"help", "Prompt process time"},
  2193. {"value", (uint64_t) data.at("t_prompt_processing_total") / 1.e3}
  2194. }, {
  2195. {"name", "tokens_predicted_total"},
  2196. {"help", "Number of generation tokens processed."},
  2197. {"value", (uint64_t) data.at("n_tokens_predicted_total")}
  2198. }, {
  2199. {"name", "tokens_predicted_seconds_total"},
  2200. {"help", "Predict process time"},
  2201. {"value", (uint64_t) data.at("t_tokens_generation_total") / 1.e3}
  2202. }, {
  2203. {"name", "n_decode_total"},
  2204. {"help", "Total number of llama_decode() calls"},
  2205. {"value", n_decode_total}
  2206. }, {
  2207. {"name", "n_busy_slots_per_decode"},
  2208. {"help", "Average number of busy slots per llama_decode() call"},
  2209. {"value", (float) n_busy_slots_total / (float) n_decode_total}
  2210. }}},
  2211. {"gauge", {{
  2212. {"name", "prompt_tokens_seconds"},
  2213. {"help", "Average prompt throughput in tokens/s."},
  2214. {"value", n_prompt_tokens_processed ? 1.e3 / t_prompt_processing * n_prompt_tokens_processed : 0.}
  2215. },{
  2216. {"name", "predicted_tokens_seconds"},
  2217. {"help", "Average generation throughput in tokens/s."},
  2218. {"value", n_tokens_predicted ? 1.e3 / t_tokens_generation * n_tokens_predicted : 0.}
  2219. },{
  2220. {"name", "kv_cache_usage_ratio"},
  2221. {"help", "KV-cache usage. 1 means 100 percent usage."},
  2222. {"value", 1. * kv_cache_used_cells / params.n_ctx}
  2223. },{
  2224. {"name", "kv_cache_tokens"},
  2225. {"help", "KV-cache tokens."},
  2226. {"value", (uint64_t) data.at("kv_cache_tokens_count")}
  2227. },{
  2228. {"name", "requests_processing"},
  2229. {"help", "Number of request processing."},
  2230. {"value", (uint64_t) data.at("processing")}
  2231. },{
  2232. {"name", "requests_deferred"},
  2233. {"help", "Number of request deferred."},
  2234. {"value", (uint64_t) data.at("deferred")}
  2235. }}}
  2236. };
  2237. std::stringstream prometheus;
  2238. for (const auto & el : all_metrics_def.items()) {
  2239. const auto & type = el.key();
  2240. const auto & metrics_def = el.value();
  2241. for (const auto & metric_def : metrics_def) {
  2242. const std::string name = metric_def.at("name");
  2243. const std::string help = metric_def.at("help");
  2244. auto value = json_value(metric_def, "value", 0.);
  2245. prometheus << "# HELP llamacpp:" << name << " " << help << "\n"
  2246. << "# TYPE llamacpp:" << name << " " << type << "\n"
  2247. << "llamacpp:" << name << " " << value << "\n";
  2248. }
  2249. }
  2250. const int64_t t_start = data.at("t_start");
  2251. res.set_header("Process-Start-Time-Unix", std::to_string(t_start));
  2252. res.set_content(prometheus.str(), "text/plain; version=0.0.4");
  2253. res.status = 200; // HTTP OK
  2254. };
  2255. const auto handle_slots_save = [&ctx_server, &res_error, &res_ok, &params](const httplib::Request & req, httplib::Response & res, int id_slot) {
  2256. json request_data = json::parse(req.body);
  2257. std::string filename = request_data.at("filename");
  2258. if (!fs_validate_filename(filename)) {
  2259. res_error(res, format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  2260. return;
  2261. }
  2262. std::string filepath = params.slot_save_path + filename;
  2263. server_task task;
  2264. task.type = SERVER_TASK_TYPE_SLOT_SAVE;
  2265. task.data = {
  2266. { "id_slot", id_slot },
  2267. { "filename", filename },
  2268. { "filepath", filepath },
  2269. };
  2270. const int id_task = ctx_server.queue_tasks.post(task);
  2271. ctx_server.queue_results.add_waiting_task_id(id_task);
  2272. server_task_result result = ctx_server.queue_results.recv(id_task);
  2273. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2274. if (result.error) {
  2275. res_error(res, result.data);
  2276. } else {
  2277. res_ok(res, result.data);
  2278. }
  2279. };
  2280. const auto handle_slots_restore = [&ctx_server, &res_error, &res_ok, &params](const httplib::Request & req, httplib::Response & res, int id_slot) {
  2281. json request_data = json::parse(req.body);
  2282. std::string filename = request_data.at("filename");
  2283. if (!fs_validate_filename(filename)) {
  2284. res_error(res, format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  2285. return;
  2286. }
  2287. std::string filepath = params.slot_save_path + filename;
  2288. server_task task;
  2289. task.type = SERVER_TASK_TYPE_SLOT_RESTORE;
  2290. task.data = {
  2291. { "id_slot", id_slot },
  2292. { "filename", filename },
  2293. { "filepath", filepath },
  2294. };
  2295. const int id_task = ctx_server.queue_tasks.post(task);
  2296. ctx_server.queue_results.add_waiting_task_id(id_task);
  2297. server_task_result result = ctx_server.queue_results.recv(id_task);
  2298. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2299. if (result.error) {
  2300. res_error(res, result.data);
  2301. } else {
  2302. res_ok(res, result.data);
  2303. }
  2304. };
  2305. const auto handle_slots_erase = [&ctx_server, &res_error, &res_ok](const httplib::Request & /* req */, httplib::Response & res, int id_slot) {
  2306. server_task task;
  2307. task.type = SERVER_TASK_TYPE_SLOT_ERASE;
  2308. task.data = {
  2309. { "id_slot", id_slot },
  2310. };
  2311. const int id_task = ctx_server.queue_tasks.post(task);
  2312. ctx_server.queue_results.add_waiting_task_id(id_task);
  2313. server_task_result result = ctx_server.queue_results.recv(id_task);
  2314. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2315. if (result.error) {
  2316. res_error(res, result.data);
  2317. } else {
  2318. res_ok(res, result.data);
  2319. }
  2320. };
  2321. const auto handle_slots_action = [&params, &res_error, &handle_slots_save, &handle_slots_restore, &handle_slots_erase](const httplib::Request & req, httplib::Response & res) {
  2322. if (params.slot_save_path.empty()) {
  2323. res_error(res, format_error_response("This server does not support slots action. Start it with `--slot-save-path`", ERROR_TYPE_NOT_SUPPORTED));
  2324. return;
  2325. }
  2326. std::string id_slot_str = req.path_params.at("id_slot");
  2327. int id_slot;
  2328. try {
  2329. id_slot = std::stoi(id_slot_str);
  2330. } catch (const std::exception &) {
  2331. res_error(res, format_error_response("Invalid slot ID", ERROR_TYPE_INVALID_REQUEST));
  2332. return;
  2333. }
  2334. std::string action = req.get_param_value("action");
  2335. if (action == "save") {
  2336. handle_slots_save(req, res, id_slot);
  2337. } else if (action == "restore") {
  2338. handle_slots_restore(req, res, id_slot);
  2339. } else if (action == "erase") {
  2340. handle_slots_erase(req, res, id_slot);
  2341. } else {
  2342. res_error(res, format_error_response("Invalid action", ERROR_TYPE_INVALID_REQUEST));
  2343. }
  2344. };
  2345. const auto handle_props = [&ctx_server, &res_ok](const httplib::Request &, httplib::Response & res) {
  2346. json data = {
  2347. { "default_generation_settings", ctx_server.default_generation_settings_for_props },
  2348. { "total_slots", ctx_server.params_base.n_parallel },
  2349. { "chat_template", llama_get_chat_template(ctx_server.model) },
  2350. };
  2351. res_ok(res, data);
  2352. };
  2353. const auto handle_props_change = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2354. if (!ctx_server.params_base.endpoint_props) {
  2355. res_error(res, format_error_response("This server does not support changing global properties. Start it with `--props`", ERROR_TYPE_NOT_SUPPORTED));
  2356. return;
  2357. }
  2358. json data = json::parse(req.body);
  2359. // update any props here
  2360. res_ok(res, {{ "success", true }});
  2361. };
  2362. const auto handle_completions_generic = [&ctx_server, &res_error, &res_ok](server_task_inf_type inf_type, json & data, httplib::Response & res) {
  2363. if (ctx_server.params_base.embedding) {
  2364. res_error(res, format_error_response("This server does not support completions. Start it without `--embeddings`", ERROR_TYPE_NOT_SUPPORTED));
  2365. return;
  2366. }
  2367. std::vector<server_task> tasks = ctx_server.create_tasks_inference(data, inf_type);
  2368. ctx_server.queue_results.add_waiting_tasks(tasks);
  2369. ctx_server.queue_tasks.post(tasks);
  2370. bool stream = json_value(data, "stream", false);
  2371. const auto task_ids = server_task::get_list_id(tasks);
  2372. if (!stream) {
  2373. ctx_server.receive_cmpl_results(task_ids, [&](std::vector<server_task_result> & results) {
  2374. if (results.size() == 1) {
  2375. // single result
  2376. res_ok(res, results[0].data);
  2377. } else {
  2378. // multiple results (multitask)
  2379. json arr = json::array();
  2380. for (const auto & res : results) {
  2381. arr.push_back(res.data);
  2382. }
  2383. res_ok(res, arr);
  2384. }
  2385. }, [&](const json & error_data) {
  2386. res_error(res, error_data);
  2387. });
  2388. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  2389. } else {
  2390. const auto chunked_content_provider = [task_ids, &ctx_server](size_t, httplib::DataSink & sink) {
  2391. ctx_server.receive_cmpl_results_stream(task_ids, [&](const server_task_result & result) -> bool {
  2392. return server_sent_event(sink, "data", result.data);
  2393. }, [&](const json & error_data) {
  2394. server_sent_event(sink, "error", error_data);
  2395. });
  2396. sink.done();
  2397. return false;
  2398. };
  2399. auto on_complete = [task_ids, &ctx_server] (bool) {
  2400. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  2401. };
  2402. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2403. }
  2404. };
  2405. const auto handle_completions = [&handle_completions_generic](const httplib::Request & req, httplib::Response & res) {
  2406. json data = json::parse(req.body);
  2407. return handle_completions_generic(SERVER_TASK_INF_TYPE_COMPLETION, data, res);
  2408. };
  2409. const auto handle_infill = [&ctx_server, &res_error, &handle_completions_generic](const httplib::Request & req, httplib::Response & res) {
  2410. // check model compatibility
  2411. std::string err;
  2412. if (llama_token_fim_pre(ctx_server.model) == LLAMA_TOKEN_NULL) {
  2413. err += "prefix token is missing. ";
  2414. }
  2415. if (llama_token_fim_suf(ctx_server.model) == LLAMA_TOKEN_NULL) {
  2416. err += "suffix token is missing. ";
  2417. }
  2418. if (llama_token_fim_mid(ctx_server.model) == LLAMA_TOKEN_NULL) {
  2419. err += "middle token is missing. ";
  2420. }
  2421. if (!err.empty()) {
  2422. res_error(res, format_error_response(string_format("Infill is not supported by this model: %s", err.c_str()), ERROR_TYPE_NOT_SUPPORTED));
  2423. return;
  2424. }
  2425. json data = json::parse(req.body);
  2426. // validate input
  2427. if (!data.contains("input_prefix")) {
  2428. res_error(res, format_error_response("\"input_prefix\" is required", ERROR_TYPE_INVALID_REQUEST));
  2429. }
  2430. if (!data.contains("input_suffix")) {
  2431. res_error(res, format_error_response("\"input_suffix\" is required", ERROR_TYPE_INVALID_REQUEST));
  2432. }
  2433. if (data.contains("input_extra") && !data.at("input_extra").is_array()) {
  2434. res_error(res, format_error_response("\"input_extra\" must be an array of {\"filename\": string, \"text\": string}", ERROR_TYPE_INVALID_REQUEST));
  2435. return;
  2436. }
  2437. json input_extra = json_value(data, "input_extra", json::array());
  2438. for (const auto & chunk : input_extra) {
  2439. // { "text": string, "filename": string }
  2440. if (!chunk.contains("text") || !chunk.at("text").is_string()) {
  2441. res_error(res, format_error_response("extra_context chunk must contain a \"text\" field with a string value", ERROR_TYPE_INVALID_REQUEST));
  2442. return;
  2443. }
  2444. // filename is optional
  2445. if (chunk.contains("filename") && !chunk.at("filename").is_string()) {
  2446. res_error(res, format_error_response("extra_context chunk's \"filename\" field must be a string", ERROR_TYPE_INVALID_REQUEST));
  2447. return;
  2448. }
  2449. }
  2450. data["input_extra"] = input_extra; // default to empty array if it's not exist
  2451. return handle_completions_generic(SERVER_TASK_INF_TYPE_INFILL, data, res);
  2452. };
  2453. // TODO: maybe merge this function with "handle_completions_generic"
  2454. const auto handle_chat_completions = [&ctx_server, &params, &res_error, &res_ok, verbose](const httplib::Request & req, httplib::Response & res) {
  2455. if (ctx_server.params_base.embedding) {
  2456. res_error(res, format_error_response("This server does not support completions. Start it without `--embeddings`", ERROR_TYPE_NOT_SUPPORTED));
  2457. return;
  2458. }
  2459. json data = oaicompat_completion_params_parse(ctx_server.model, json::parse(req.body), params.chat_template);
  2460. std::vector<server_task> tasks = ctx_server.create_tasks_inference(data, SERVER_TASK_INF_TYPE_COMPLETION);
  2461. ctx_server.queue_results.add_waiting_tasks(tasks);
  2462. ctx_server.queue_tasks.post(tasks);
  2463. bool stream = json_value(data, "stream", false);
  2464. const auto task_ids = server_task::get_list_id(tasks);
  2465. const auto completion_id = gen_chatcmplid();
  2466. if (!stream) {
  2467. ctx_server.receive_cmpl_results(task_ids, [&](const std::vector<server_task_result> & results) {
  2468. // multitask is never support in chat completion, there is only one result
  2469. json result_oai = format_final_response_oaicompat(data, results[0].data, completion_id, /*.streaming =*/ false, verbose);
  2470. res_ok(res, result_oai);
  2471. }, [&](const json & error_data) {
  2472. res_error(res, error_data);
  2473. });
  2474. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  2475. } else {
  2476. const auto chunked_content_provider = [task_ids, &ctx_server, completion_id](size_t, httplib::DataSink & sink) {
  2477. ctx_server.receive_cmpl_results_stream(task_ids, [&](const server_task_result & result) -> bool {
  2478. std::vector<json> result_array = format_partial_response_oaicompat(result.data, completion_id);
  2479. for (auto & event_data : result_array) {
  2480. if (event_data.empty()) {
  2481. continue; // skip the stop token
  2482. }
  2483. if (!server_sent_event(sink, "data", event_data)) {
  2484. return false; // connection is closed
  2485. }
  2486. }
  2487. return true; // ok
  2488. }, [&](const json & error_data) {
  2489. server_sent_event(sink, "error", error_data);
  2490. });
  2491. static const std::string ev_done = "data: [DONE]\n\n";
  2492. sink.write(ev_done.data(), ev_done.size());
  2493. sink.done();
  2494. return true;
  2495. };
  2496. auto on_complete = [task_ids, &ctx_server] (bool) {
  2497. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  2498. };
  2499. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2500. }
  2501. };
  2502. const auto handle_models = [&params, &ctx_server](const httplib::Request &, httplib::Response & res) {
  2503. json models = {
  2504. {"object", "list"},
  2505. {"data", {
  2506. {
  2507. {"id", params.model_alias},
  2508. {"object", "model"},
  2509. {"created", std::time(0)},
  2510. {"owned_by", "llamacpp"},
  2511. {"meta", ctx_server.model_meta()}
  2512. },
  2513. }}
  2514. };
  2515. res.set_content(models.dump(), MIMETYPE_JSON);
  2516. };
  2517. const auto handle_tokenize = [&ctx_server, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2518. const json body = json::parse(req.body);
  2519. json tokens_response = json::array();
  2520. if (body.count("content") != 0) {
  2521. const bool add_special = json_value(body, "add_special", false);
  2522. const bool with_pieces = json_value(body, "with_pieces", false);
  2523. llama_tokens tokens = tokenize_mixed(ctx_server.ctx, body.at("content"), add_special, true);
  2524. if (with_pieces) {
  2525. for (const auto& token : tokens) {
  2526. std::string piece = common_token_to_piece(ctx_server.ctx, token);
  2527. json piece_json;
  2528. // Check if the piece is valid UTF-8
  2529. if (is_valid_utf8(piece)) {
  2530. piece_json = piece;
  2531. } else {
  2532. // If not valid UTF-8, store as array of byte values
  2533. piece_json = json::array();
  2534. for (unsigned char c : piece) {
  2535. piece_json.push_back(static_cast<int>(c));
  2536. }
  2537. }
  2538. tokens_response.push_back({
  2539. {"id", token},
  2540. {"piece", piece_json}
  2541. });
  2542. }
  2543. } else {
  2544. tokens_response = tokens;
  2545. }
  2546. }
  2547. const json data = format_tokenizer_response(tokens_response);
  2548. res_ok(res, data);
  2549. };
  2550. const auto handle_detokenize = [&ctx_server, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2551. const json body = json::parse(req.body);
  2552. std::string content;
  2553. if (body.count("tokens") != 0) {
  2554. const llama_tokens tokens = body.at("tokens");
  2555. content = tokens_to_str(ctx_server.ctx, tokens.cbegin(), tokens.cend());
  2556. }
  2557. const json data = format_detokenized_response(content);
  2558. res_ok(res, data);
  2559. };
  2560. const auto handle_embeddings = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2561. const json body = json::parse(req.body);
  2562. bool is_openai = false;
  2563. // an input prompt can be a string or a list of tokens (integer)
  2564. json prompt;
  2565. if (body.count("input") != 0) {
  2566. is_openai = true;
  2567. prompt = body.at("input");
  2568. } else if (body.count("content") != 0) {
  2569. // with "content", we only support single prompt
  2570. prompt = std::vector<std::string>{body.at("content")};
  2571. } else {
  2572. res_error(res, format_error_response("\"input\" or \"content\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  2573. return;
  2574. }
  2575. // create and queue the task
  2576. json responses = json::array();
  2577. bool error = false;
  2578. {
  2579. std::vector<server_task> tasks = ctx_server.create_tasks_inference({{"prompt", prompt}}, SERVER_TASK_INF_TYPE_EMBEDDING);
  2580. ctx_server.queue_results.add_waiting_tasks(tasks);
  2581. ctx_server.queue_tasks.post(tasks);
  2582. // get the result
  2583. std::unordered_set<int> task_ids = server_task::get_list_id(tasks);
  2584. ctx_server.receive_cmpl_results(task_ids, [&](std::vector<server_task_result> & results) {
  2585. for (const auto & res : results) {
  2586. responses.push_back(res.data);
  2587. }
  2588. }, [&](const json & error_data) {
  2589. res_error(res, error_data);
  2590. error = true;
  2591. });
  2592. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  2593. }
  2594. if (error) {
  2595. return;
  2596. }
  2597. // write JSON response
  2598. json root = is_openai
  2599. ? format_embeddings_response_oaicompat(body, responses)
  2600. : responses[0];
  2601. res_ok(res, root);
  2602. };
  2603. const auto handle_rerank = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2604. if (!ctx_server.params_base.reranking || ctx_server.params_base.embedding) {
  2605. res_error(res, format_error_response("This server does not support reranking. Start it with `--reranking` and without `--embedding`", ERROR_TYPE_NOT_SUPPORTED));
  2606. return;
  2607. }
  2608. const json body = json::parse(req.body);
  2609. // TODO: implement
  2610. //int top_n = 1;
  2611. //if (body.count("top_n") != 1) {
  2612. // top_n = body.at("top_n");
  2613. //} else {
  2614. // res_error(res, format_error_response("\"top_n\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  2615. // return;
  2616. //}
  2617. json query;
  2618. if (body.count("query") == 1) {
  2619. query = body.at("query");
  2620. if (!query.is_string()) {
  2621. res_error(res, format_error_response("\"query\" must be a string", ERROR_TYPE_INVALID_REQUEST));
  2622. return;
  2623. }
  2624. } else {
  2625. res_error(res, format_error_response("\"query\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  2626. return;
  2627. }
  2628. std::vector<std::string> documents = json_value(body, "documents", std::vector<std::string>());
  2629. if (documents.empty()) {
  2630. res_error(res, format_error_response("\"documents\" must be a non-empty string array", ERROR_TYPE_INVALID_REQUEST));
  2631. return;
  2632. }
  2633. // construct prompt object: array of ["query", "doc0", "doc1", ...]
  2634. json prompt;
  2635. prompt.push_back(query);
  2636. for (const auto & doc : documents) {
  2637. prompt.push_back(doc);
  2638. }
  2639. LOG_DBG("rerank prompt: %s\n", prompt.dump().c_str());
  2640. // create and queue the task
  2641. json responses = json::array();
  2642. bool error = false;
  2643. {
  2644. std::vector<server_task> tasks = ctx_server.create_tasks_inference({{"prompt", prompt}}, SERVER_TASK_INF_TYPE_RERANK);
  2645. ctx_server.queue_results.add_waiting_tasks(tasks);
  2646. ctx_server.queue_tasks.post(tasks);
  2647. // get the result
  2648. std::unordered_set<int> task_ids = server_task::get_list_id(tasks);
  2649. ctx_server.receive_cmpl_results(task_ids, [&](std::vector<server_task_result> & results) {
  2650. for (const auto & res : results) {
  2651. responses.push_back(res.data);
  2652. }
  2653. }, [&](const json & error_data) {
  2654. res_error(res, error_data);
  2655. error = true;
  2656. });
  2657. }
  2658. if (error) {
  2659. return;
  2660. }
  2661. // write JSON response
  2662. json root = format_response_rerank(body, responses);
  2663. res_ok(res, root);
  2664. };
  2665. const auto handle_lora_adapters_list = [&](const httplib::Request &, httplib::Response & res) {
  2666. json result = json::array();
  2667. for (size_t i = 0; i < ctx_server.loras.size(); ++i) {
  2668. auto & lora = ctx_server.loras[i];
  2669. result.push_back({
  2670. {"id", i},
  2671. {"path", lora.path},
  2672. {"scale", lora.scale},
  2673. });
  2674. }
  2675. res_ok(res, result);
  2676. res.status = 200; // HTTP OK
  2677. };
  2678. const auto handle_lora_adapters_apply = [&](const httplib::Request & req, httplib::Response & res) {
  2679. const std::vector<json> body = json::parse(req.body);
  2680. int max_idx = ctx_server.loras.size();
  2681. // clear existing value
  2682. for (auto & lora : ctx_server.loras) {
  2683. lora.scale = 0.0f;
  2684. }
  2685. // set value
  2686. for (auto entry : body) {
  2687. int id = entry.at("id");
  2688. float scale = entry.at("scale");
  2689. if (0 <= id && id < max_idx) {
  2690. ctx_server.loras[id].scale = scale;
  2691. } else {
  2692. throw std::runtime_error("invalid adapter id");
  2693. }
  2694. }
  2695. server_task task;
  2696. task.type = SERVER_TASK_TYPE_SET_LORA;
  2697. const int id_task = ctx_server.queue_tasks.post(task);
  2698. ctx_server.queue_results.add_waiting_task_id(id_task);
  2699. server_task_result result = ctx_server.queue_results.recv(id_task);
  2700. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2701. res_ok(res, result.data);
  2702. res.status = 200; // HTTP OK
  2703. };
  2704. //
  2705. // Router
  2706. //
  2707. // register static assets routes
  2708. if (!params.public_path.empty()) {
  2709. // Set the base directory for serving static files
  2710. bool is_found = svr->set_mount_point("/", params.public_path);
  2711. if (!is_found) {
  2712. LOG_ERR("%s: static assets path not found: %s\n", __func__, params.public_path.c_str());
  2713. return 1;
  2714. }
  2715. } else {
  2716. // using embedded static index.html
  2717. svr->Get("/", [](const httplib::Request &, httplib::Response & res) {
  2718. res.set_content(reinterpret_cast<const char*>(index_html), index_html_len, "text/html; charset=utf-8");
  2719. return false;
  2720. });
  2721. }
  2722. // register API routes
  2723. svr->Get ("/health", handle_health); // public endpoint (no API key check)
  2724. svr->Get ("/metrics", handle_metrics);
  2725. svr->Get ("/props", handle_props);
  2726. svr->Post("/props", handle_props_change);
  2727. svr->Get ("/models", handle_models); // public endpoint (no API key check)
  2728. svr->Get ("/v1/models", handle_models); // public endpoint (no API key check)
  2729. svr->Post("/completion", handle_completions); // legacy
  2730. svr->Post("/completions", handle_completions);
  2731. svr->Post("/v1/completions", handle_completions);
  2732. svr->Post("/chat/completions", handle_chat_completions);
  2733. svr->Post("/v1/chat/completions", handle_chat_completions);
  2734. svr->Post("/infill", handle_infill);
  2735. svr->Post("/embedding", handle_embeddings); // legacy
  2736. svr->Post("/embeddings", handle_embeddings);
  2737. svr->Post("/v1/embeddings", handle_embeddings);
  2738. svr->Post("/rerank", handle_rerank);
  2739. svr->Post("/reranking", handle_rerank);
  2740. svr->Post("/v1/rerank", handle_rerank);
  2741. svr->Post("/v1/reranking", handle_rerank);
  2742. svr->Post("/tokenize", handle_tokenize);
  2743. svr->Post("/detokenize", handle_detokenize);
  2744. // LoRA adapters hotswap
  2745. svr->Get ("/lora-adapters", handle_lora_adapters_list);
  2746. svr->Post("/lora-adapters", handle_lora_adapters_apply);
  2747. // Save & load slots
  2748. svr->Get ("/slots", handle_slots);
  2749. svr->Post("/slots/:id_slot", handle_slots_action);
  2750. //
  2751. // Start the server
  2752. //
  2753. if (params.n_threads_http < 1) {
  2754. // +2 threads for monitoring endpoints
  2755. params.n_threads_http = std::max(params.n_parallel + 2, (int32_t) std::thread::hardware_concurrency() - 1);
  2756. }
  2757. log_data["n_threads_http"] = std::to_string(params.n_threads_http);
  2758. svr->new_task_queue = [&params] { return new httplib::ThreadPool(params.n_threads_http); };
  2759. // clean up function, to be called before exit
  2760. auto clean_up = [&svr]() {
  2761. svr->stop();
  2762. llama_backend_free();
  2763. };
  2764. // bind HTTP listen port
  2765. bool was_bound = false;
  2766. if (params.port == 0) {
  2767. int bound_port = svr->bind_to_any_port(params.hostname);
  2768. if ((was_bound = (bound_port >= 0))) {
  2769. params.port = bound_port;
  2770. }
  2771. } else {
  2772. was_bound = svr->bind_to_port(params.hostname, params.port);
  2773. }
  2774. if (!was_bound) {
  2775. //LOG_ERROR("couldn't bind HTTP server socket", {
  2776. // {"hostname", params.hostname},
  2777. // {"port", params.port},
  2778. //});
  2779. LOG_ERR("%s: couldn't bind HTTP server socket, hostname: %s, port: %d\n", __func__, params.hostname.c_str(), params.port);
  2780. clean_up();
  2781. return 1;
  2782. }
  2783. // run the HTTP server in a thread
  2784. std::thread t([&]() { svr->listen_after_bind(); });
  2785. svr->wait_until_ready();
  2786. LOG_INF("%s: HTTP server is listening, hostname: %s, port: %d, http threads: %d\n", __func__, params.hostname.c_str(), params.port, params.n_threads_http);
  2787. // load the model
  2788. LOG_INF("%s: loading model\n", __func__);
  2789. if (!ctx_server.load_model(params)) {
  2790. clean_up();
  2791. t.join();
  2792. LOG_ERR("%s: exiting due to model loading error\n", __func__);
  2793. return 1;
  2794. }
  2795. ctx_server.init();
  2796. state.store(SERVER_STATE_READY);
  2797. LOG_INF("%s: model loaded\n", __func__);
  2798. // if a custom chat template is not supplied, we will use the one that comes with the model (if any)
  2799. if (params.chat_template.empty()) {
  2800. if (!ctx_server.validate_model_chat_template()) {
  2801. LOG_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__);
  2802. params.chat_template = "chatml";
  2803. }
  2804. }
  2805. // print sample chat example to make it clear which template is used
  2806. LOG_INF("%s: chat template, built_in: %d, chat_example: '%s'\n", __func__, params.chat_template.empty(), common_chat_format_example(ctx_server.model, params.chat_template).c_str());
  2807. ctx_server.queue_tasks.on_new_task(std::bind(
  2808. &server_context::process_single_task, &ctx_server, std::placeholders::_1));
  2809. ctx_server.queue_tasks.on_update_slots(std::bind(
  2810. &server_context::update_slots, &ctx_server));
  2811. shutdown_handler = [&](int) {
  2812. ctx_server.queue_tasks.terminate();
  2813. };
  2814. LOG_INF("%s: server is listening on http://%s:%d - starting the main loop\n", __func__, params.hostname.c_str(), params.port);
  2815. ctx_server.queue_tasks.start_loop();
  2816. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  2817. struct sigaction sigint_action;
  2818. sigint_action.sa_handler = signal_handler;
  2819. sigemptyset (&sigint_action.sa_mask);
  2820. sigint_action.sa_flags = 0;
  2821. sigaction(SIGINT, &sigint_action, NULL);
  2822. sigaction(SIGTERM, &sigint_action, NULL);
  2823. #elif defined (_WIN32)
  2824. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  2825. return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
  2826. };
  2827. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  2828. #endif
  2829. clean_up();
  2830. t.join();
  2831. return 0;
  2832. }