server.cpp 134 KB

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