server.cpp 131 KB

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