server.cpp 131 KB

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