server.cpp 137 KB

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