server.cpp 131 KB

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