server.cpp 139 KB

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