server.cpp 132 KB

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