server.cpp 142 KB

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