server.cpp 152 KB

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