server.cpp 126 KB

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