1
0

server.cpp 125 KB

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