server.cpp 135 KB

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