server.cpp 154 KB

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