1
0

server.cpp 140 KB

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