server.cpp 128 KB

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