server.cpp 126 KB

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