1
0

server.cpp 133 KB

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