server.cpp 138 KB

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