server.cpp 138 KB

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