server.cpp 135 KB

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