server.cpp 191 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863
  1. #include "utils.hpp"
  2. #include "arg.h"
  3. #include "common.h"
  4. #include "json-schema-to-grammar.h"
  5. #include "llama.h"
  6. #include "log.h"
  7. #include "sampling.h"
  8. #include "speculative.h"
  9. #include "mtmd.h"
  10. // Change JSON_ASSERT from assert() to GGML_ASSERT:
  11. #define JSON_ASSERT GGML_ASSERT
  12. #include "json.hpp"
  13. // mime type for sending response
  14. #define MIMETYPE_JSON "application/json; charset=utf-8"
  15. // auto generated files (see README.md for details)
  16. #include "index.html.gz.hpp"
  17. #include "loading.html.hpp"
  18. #include <atomic>
  19. #include <chrono>
  20. #include <condition_variable>
  21. #include <cstddef>
  22. #include <cinttypes>
  23. #include <deque>
  24. #include <memory>
  25. #include <mutex>
  26. #include <signal.h>
  27. #include <thread>
  28. #include <unordered_map>
  29. #include <unordered_set>
  30. using json = nlohmann::ordered_json;
  31. constexpr int HTTP_POLLING_SECONDS = 1;
  32. enum stop_type {
  33. STOP_TYPE_NONE,
  34. STOP_TYPE_EOS,
  35. STOP_TYPE_WORD,
  36. STOP_TYPE_LIMIT,
  37. };
  38. // state diagram: https://github.com/ggml-org/llama.cpp/pull/9283
  39. enum slot_state {
  40. SLOT_STATE_IDLE,
  41. SLOT_STATE_STARTED, // TODO: this state is only used for setting up the initial prompt processing; maybe merge it with launch_slot_with_task in the future
  42. SLOT_STATE_PROCESSING_PROMPT,
  43. SLOT_STATE_DONE_PROMPT,
  44. SLOT_STATE_GENERATING,
  45. };
  46. enum server_state {
  47. SERVER_STATE_LOADING_MODEL, // Server is starting up, model not fully loaded yet
  48. SERVER_STATE_READY, // Server is ready and model is loaded
  49. };
  50. enum server_task_type {
  51. SERVER_TASK_TYPE_COMPLETION,
  52. SERVER_TASK_TYPE_EMBEDDING,
  53. SERVER_TASK_TYPE_RERANK,
  54. SERVER_TASK_TYPE_INFILL,
  55. SERVER_TASK_TYPE_CANCEL,
  56. SERVER_TASK_TYPE_NEXT_RESPONSE,
  57. SERVER_TASK_TYPE_METRICS,
  58. SERVER_TASK_TYPE_SLOT_SAVE,
  59. SERVER_TASK_TYPE_SLOT_RESTORE,
  60. SERVER_TASK_TYPE_SLOT_ERASE,
  61. SERVER_TASK_TYPE_SET_LORA,
  62. };
  63. enum oaicompat_type {
  64. OAICOMPAT_TYPE_NONE,
  65. OAICOMPAT_TYPE_CHAT,
  66. OAICOMPAT_TYPE_COMPLETION,
  67. OAICOMPAT_TYPE_EMBEDDING,
  68. };
  69. // https://community.openai.com/t/openai-chat-list-of-error-codes-and-types/357791/11
  70. enum error_type {
  71. ERROR_TYPE_INVALID_REQUEST,
  72. ERROR_TYPE_AUTHENTICATION,
  73. ERROR_TYPE_SERVER,
  74. ERROR_TYPE_NOT_FOUND,
  75. ERROR_TYPE_PERMISSION,
  76. ERROR_TYPE_UNAVAILABLE, // custom error
  77. ERROR_TYPE_NOT_SUPPORTED, // custom error
  78. };
  79. struct slot_params {
  80. bool stream = true;
  81. bool cache_prompt = true; // remember the prompt to avoid reprocessing all prompt
  82. bool return_tokens = false;
  83. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  84. int32_t n_discard = 0; // number of tokens after n_keep that may be discarded when shifting context, 0 defaults to half
  85. int32_t n_predict = -1; // new tokens to predict
  86. int32_t n_indent = 0; // mininum line indentation for the generated text in number of whitespace characters
  87. int64_t t_max_prompt_ms = -1; // TODO: implement
  88. int64_t t_max_predict_ms = -1; // if positive, limit the generation phase to this time limit
  89. std::vector<common_adapter_lora_info> lora;
  90. std::vector<std::string> antiprompt;
  91. std::vector<std::string> response_fields;
  92. bool timings_per_token = false;
  93. bool post_sampling_probs = false;
  94. bool ignore_eos = false;
  95. struct common_params_sampling sampling;
  96. struct common_params_speculative speculative;
  97. // OAI-compat fields
  98. bool verbose = false;
  99. oaicompat_type oaicompat = OAICOMPAT_TYPE_NONE;
  100. std::string oaicompat_model;
  101. std::string oaicompat_cmpl_id;
  102. common_chat_format oaicompat_chat_format = COMMON_CHAT_FORMAT_CONTENT_ONLY;
  103. json to_json() const {
  104. std::vector<std::string> samplers;
  105. samplers.reserve(sampling.samplers.size());
  106. for (const auto & sampler : sampling.samplers) {
  107. samplers.emplace_back(common_sampler_type_to_str(sampler));
  108. }
  109. json lora = json::array();
  110. for (size_t i = 0; i < this->lora.size(); ++i) {
  111. lora.push_back({{"id", i}, {"scale", this->lora[i].scale}});
  112. }
  113. auto grammar_triggers = json::array();
  114. for (const auto & trigger : sampling.grammar_triggers) {
  115. server_grammar_trigger ct(std::move(trigger));
  116. grammar_triggers.push_back(ct.to_json());
  117. }
  118. return json {
  119. {"n_predict", n_predict}, // Server configured n_predict
  120. {"seed", sampling.seed},
  121. {"temperature", sampling.temp},
  122. {"dynatemp_range", sampling.dynatemp_range},
  123. {"dynatemp_exponent", sampling.dynatemp_exponent},
  124. {"top_k", sampling.top_k},
  125. {"top_p", sampling.top_p},
  126. {"min_p", sampling.min_p},
  127. {"top_n_sigma", sampling.top_n_sigma},
  128. {"xtc_probability", sampling.xtc_probability},
  129. {"xtc_threshold", sampling.xtc_threshold},
  130. {"typical_p", sampling.typ_p},
  131. {"repeat_last_n", sampling.penalty_last_n},
  132. {"repeat_penalty", sampling.penalty_repeat},
  133. {"presence_penalty", sampling.penalty_present},
  134. {"frequency_penalty", sampling.penalty_freq},
  135. {"dry_multiplier", sampling.dry_multiplier},
  136. {"dry_base", sampling.dry_base},
  137. {"dry_allowed_length", sampling.dry_allowed_length},
  138. {"dry_penalty_last_n", sampling.dry_penalty_last_n},
  139. {"dry_sequence_breakers", sampling.dry_sequence_breakers},
  140. {"mirostat", sampling.mirostat},
  141. {"mirostat_tau", sampling.mirostat_tau},
  142. {"mirostat_eta", sampling.mirostat_eta},
  143. {"stop", antiprompt},
  144. {"max_tokens", n_predict}, // User configured n_predict
  145. {"n_keep", n_keep},
  146. {"n_discard", n_discard},
  147. {"ignore_eos", sampling.ignore_eos},
  148. {"stream", stream},
  149. {"logit_bias", format_logit_bias(sampling.logit_bias)},
  150. {"n_probs", sampling.n_probs},
  151. {"min_keep", sampling.min_keep},
  152. {"grammar", sampling.grammar},
  153. {"grammar_lazy", sampling.grammar_lazy},
  154. {"grammar_triggers", grammar_triggers},
  155. {"preserved_tokens", sampling.preserved_tokens},
  156. {"chat_format", common_chat_format_name(oaicompat_chat_format)},
  157. {"samplers", samplers},
  158. {"speculative.n_max", speculative.n_max},
  159. {"speculative.n_min", speculative.n_min},
  160. {"speculative.p_min", speculative.p_min},
  161. {"timings_per_token", timings_per_token},
  162. {"post_sampling_probs", post_sampling_probs},
  163. {"lora", lora},
  164. };
  165. }
  166. };
  167. struct server_task {
  168. int id = -1; // to be filled by server_queue
  169. int index = -1; // used when there are multiple prompts (batch request)
  170. server_task_type type;
  171. // used by SERVER_TASK_TYPE_CANCEL
  172. int id_target = -1;
  173. // used by SERVER_TASK_TYPE_INFERENCE
  174. slot_params params;
  175. server_tokens prompt_tokens;
  176. int id_selected_slot = -1;
  177. // used by SERVER_TASK_TYPE_SLOT_SAVE, SERVER_TASK_TYPE_SLOT_RESTORE, SERVER_TASK_TYPE_SLOT_ERASE
  178. struct slot_action {
  179. int slot_id;
  180. std::string filename;
  181. std::string filepath;
  182. };
  183. slot_action slot_action;
  184. // used by SERVER_TASK_TYPE_METRICS
  185. bool metrics_reset_bucket = false;
  186. // used by SERVER_TASK_TYPE_SET_LORA
  187. std::vector<common_adapter_lora_info> set_lora;
  188. server_task(server_task_type type) : type(type) {}
  189. static slot_params params_from_json_cmpl(
  190. const llama_context * ctx,
  191. const common_params & params_base,
  192. const json & data) {
  193. const llama_model * model = llama_get_model(ctx);
  194. const llama_vocab * vocab = llama_model_get_vocab(model);
  195. slot_params params;
  196. // Sampling parameter defaults are loaded from the global server context (but individual requests can still override them)
  197. slot_params defaults;
  198. defaults.sampling = params_base.sampling;
  199. defaults.speculative = params_base.speculative;
  200. // enabling this will output extra debug information in the HTTP responses from the server
  201. params.verbose = params_base.verbosity > 9;
  202. params.timings_per_token = json_value(data, "timings_per_token", false);
  203. params.stream = json_value(data, "stream", false);
  204. params.cache_prompt = json_value(data, "cache_prompt", true);
  205. params.return_tokens = json_value(data, "return_tokens", false);
  206. params.n_predict = json_value(data, "n_predict", json_value(data, "max_tokens", defaults.n_predict));
  207. params.n_indent = json_value(data, "n_indent", defaults.n_indent);
  208. params.n_keep = json_value(data, "n_keep", defaults.n_keep);
  209. params.n_discard = json_value(data, "n_discard", defaults.n_discard);
  210. //params.t_max_prompt_ms = json_value(data, "t_max_prompt_ms", defaults.t_max_prompt_ms); // TODO: implement
  211. params.t_max_predict_ms = json_value(data, "t_max_predict_ms", defaults.t_max_predict_ms);
  212. params.response_fields = json_value(data, "response_fields", std::vector<std::string>());
  213. params.sampling.top_k = json_value(data, "top_k", defaults.sampling.top_k);
  214. params.sampling.top_p = json_value(data, "top_p", defaults.sampling.top_p);
  215. params.sampling.min_p = json_value(data, "min_p", defaults.sampling.min_p);
  216. params.sampling.top_n_sigma = json_value(data, "top_n_sigma", defaults.sampling.top_n_sigma);
  217. params.sampling.xtc_probability = json_value(data, "xtc_probability", defaults.sampling.xtc_probability);
  218. params.sampling.xtc_threshold = json_value(data, "xtc_threshold", defaults.sampling.xtc_threshold);
  219. params.sampling.typ_p = json_value(data, "typical_p", defaults.sampling.typ_p);
  220. params.sampling.temp = json_value(data, "temperature", defaults.sampling.temp);
  221. params.sampling.dynatemp_range = json_value(data, "dynatemp_range", defaults.sampling.dynatemp_range);
  222. params.sampling.dynatemp_exponent = json_value(data, "dynatemp_exponent", defaults.sampling.dynatemp_exponent);
  223. params.sampling.penalty_last_n = json_value(data, "repeat_last_n", defaults.sampling.penalty_last_n);
  224. params.sampling.penalty_repeat = json_value(data, "repeat_penalty", defaults.sampling.penalty_repeat);
  225. params.sampling.penalty_freq = json_value(data, "frequency_penalty", defaults.sampling.penalty_freq);
  226. params.sampling.penalty_present = json_value(data, "presence_penalty", defaults.sampling.penalty_present);
  227. params.sampling.dry_multiplier = json_value(data, "dry_multiplier", defaults.sampling.dry_multiplier);
  228. params.sampling.dry_base = json_value(data, "dry_base", defaults.sampling.dry_base);
  229. params.sampling.dry_allowed_length = json_value(data, "dry_allowed_length", defaults.sampling.dry_allowed_length);
  230. params.sampling.dry_penalty_last_n = json_value(data, "dry_penalty_last_n", defaults.sampling.dry_penalty_last_n);
  231. params.sampling.mirostat = json_value(data, "mirostat", defaults.sampling.mirostat);
  232. params.sampling.mirostat_tau = json_value(data, "mirostat_tau", defaults.sampling.mirostat_tau);
  233. params.sampling.mirostat_eta = json_value(data, "mirostat_eta", defaults.sampling.mirostat_eta);
  234. params.sampling.seed = json_value(data, "seed", defaults.sampling.seed);
  235. params.sampling.n_probs = json_value(data, "n_probs", defaults.sampling.n_probs);
  236. params.sampling.min_keep = json_value(data, "min_keep", defaults.sampling.min_keep);
  237. params.post_sampling_probs = json_value(data, "post_sampling_probs", defaults.post_sampling_probs);
  238. params.speculative.n_min = json_value(data, "speculative.n_min", defaults.speculative.n_min);
  239. params.speculative.n_max = json_value(data, "speculative.n_max", defaults.speculative.n_max);
  240. params.speculative.p_min = json_value(data, "speculative.p_min", defaults.speculative.p_min);
  241. params.speculative.n_min = std::min(params.speculative.n_max, params.speculative.n_min);
  242. params.speculative.n_min = std::max(params.speculative.n_min, 0);
  243. params.speculative.n_max = std::max(params.speculative.n_max, 0);
  244. // Use OpenAI API logprobs only if n_probs wasn't provided
  245. if (data.contains("logprobs") && params.sampling.n_probs == defaults.sampling.n_probs){
  246. params.sampling.n_probs = json_value(data, "logprobs", defaults.sampling.n_probs);
  247. }
  248. if (data.contains("lora")) {
  249. if (data.at("lora").is_array()) {
  250. params.lora = parse_lora_request(params_base.lora_adapters, data.at("lora"));
  251. } else {
  252. throw std::runtime_error("Error: 'lora' must be an array of objects with 'id' and 'scale' fields");
  253. }
  254. } else {
  255. params.lora = params_base.lora_adapters;
  256. }
  257. // TODO: add more sanity checks for the input parameters
  258. if (params.sampling.penalty_last_n < -1) {
  259. throw std::runtime_error("Error: repeat_last_n must be >= -1");
  260. }
  261. if (params.sampling.dry_penalty_last_n < -1) {
  262. throw std::runtime_error("Error: dry_penalty_last_n must be >= -1");
  263. }
  264. if (params.sampling.penalty_last_n == -1) {
  265. // note: should be the slot's context and not the full context, but it's ok
  266. params.sampling.penalty_last_n = llama_n_ctx(ctx);
  267. }
  268. if (params.sampling.dry_penalty_last_n == -1) {
  269. params.sampling.dry_penalty_last_n = llama_n_ctx(ctx);
  270. }
  271. if (params.sampling.dry_base < 1.0f) {
  272. params.sampling.dry_base = defaults.sampling.dry_base;
  273. }
  274. // sequence breakers for DRY
  275. {
  276. // Currently, this is not compatible with TextGen WebUI, Koboldcpp and SillyTavern format
  277. // Ref: https://github.com/oobabooga/text-generation-webui/blob/d1af7a41ade7bd3c3a463bfa640725edb818ebaf/extensions/openai/typing.py#L39
  278. if (data.contains("dry_sequence_breakers")) {
  279. params.sampling.dry_sequence_breakers = json_value(data, "dry_sequence_breakers", std::vector<std::string>());
  280. if (params.sampling.dry_sequence_breakers.empty()) {
  281. throw std::runtime_error("Error: dry_sequence_breakers must be a non-empty array of strings");
  282. }
  283. }
  284. }
  285. // process "json_schema" and "grammar"
  286. if (data.contains("json_schema") && !data.contains("grammar")) {
  287. try {
  288. auto schema = json_value(data, "json_schema", json::object());
  289. SRV_DBG("JSON schema: %s\n", schema.dump(2).c_str());
  290. params.sampling.grammar = json_schema_to_grammar(schema);
  291. SRV_DBG("Converted grammar: %s\n", params.sampling.grammar.c_str());
  292. } catch (const std::exception & e) {
  293. throw std::runtime_error(std::string("\"json_schema\": ") + e.what());
  294. }
  295. } else {
  296. params.sampling.grammar = json_value(data, "grammar", defaults.sampling.grammar);
  297. SRV_DBG("Grammar: %s\n", params.sampling.grammar.c_str());
  298. params.sampling.grammar_lazy = json_value(data, "grammar_lazy", defaults.sampling.grammar_lazy);
  299. SRV_DBG("Grammar lazy: %s\n", params.sampling.grammar_lazy ? "true" : "false");
  300. }
  301. {
  302. auto it = data.find("chat_format");
  303. if (it != data.end()) {
  304. params.oaicompat_chat_format = static_cast<common_chat_format>(it->get<int>());
  305. SRV_INF("Chat format: %s\n", common_chat_format_name(params.oaicompat_chat_format).c_str());
  306. } else {
  307. params.oaicompat_chat_format = defaults.oaicompat_chat_format;
  308. }
  309. }
  310. {
  311. const auto preserved_tokens = data.find("preserved_tokens");
  312. if (preserved_tokens != data.end()) {
  313. for (const auto & t : *preserved_tokens) {
  314. auto ids = common_tokenize(vocab, t.get<std::string>(), /* add_special= */ false, /* parse_special= */ true);
  315. if (ids.size() == 1) {
  316. SRV_DBG("Preserved token: %d\n", ids[0]);
  317. params.sampling.preserved_tokens.insert(ids[0]);
  318. } else {
  319. // This may happen when using a tool call style meant for a model with special tokens to preserve on a model without said tokens.
  320. SRV_DBG("Not preserved because more than 1 token: %s\n", t.get<std::string>().c_str());
  321. }
  322. }
  323. }
  324. const auto grammar_triggers = data.find("grammar_triggers");
  325. if (grammar_triggers != data.end()) {
  326. for (const auto & t : *grammar_triggers) {
  327. server_grammar_trigger ct(t);
  328. if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_WORD) {
  329. const auto & word = ct.value.value;
  330. auto ids = common_tokenize(vocab, word, /* add_special= */ false, /* parse_special= */ true);
  331. if (ids.size() == 1) {
  332. auto token = ids[0];
  333. if (std::find(params.sampling.preserved_tokens.begin(), params.sampling.preserved_tokens.end(), (llama_token) token) == params.sampling.preserved_tokens.end()) {
  334. throw std::runtime_error("Grammar trigger word should be marked as preserved token: " + word);
  335. }
  336. SRV_DBG("Grammar trigger token: %d (`%s`)\n", token, word.c_str());
  337. common_grammar_trigger trigger;
  338. trigger.type = COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN;
  339. trigger.value = word;
  340. trigger.token = token;
  341. params.sampling.grammar_triggers.push_back(std::move(trigger));
  342. } else {
  343. SRV_DBG("Grammar trigger word: `%s`\n", word.c_str());
  344. params.sampling.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, word});
  345. }
  346. } else {
  347. params.sampling.grammar_triggers.push_back(std::move(ct.value));
  348. }
  349. }
  350. }
  351. if (params.sampling.grammar_lazy && params.sampling.grammar_triggers.empty()) {
  352. throw std::runtime_error("Error: no triggers set for lazy grammar!");
  353. }
  354. }
  355. {
  356. params.sampling.logit_bias.clear();
  357. params.ignore_eos = json_value(data, "ignore_eos", false);
  358. const auto & logit_bias = data.find("logit_bias");
  359. if (logit_bias != data.end() && logit_bias->is_array()) {
  360. const int n_vocab = llama_vocab_n_tokens(vocab);
  361. for (const auto & el : *logit_bias) {
  362. // TODO: we may want to throw errors here, in case "el" is incorrect
  363. if (el.is_array() && el.size() == 2) {
  364. float bias;
  365. if (el[1].is_number()) {
  366. bias = el[1].get<float>();
  367. } else if (el[1].is_boolean() && !el[1].get<bool>()) {
  368. bias = -INFINITY;
  369. } else {
  370. continue;
  371. }
  372. if (el[0].is_number_integer()) {
  373. llama_token tok = el[0].get<llama_token>();
  374. if (tok >= 0 && tok < n_vocab) {
  375. params.sampling.logit_bias.push_back({tok, bias});
  376. }
  377. } else if (el[0].is_string()) {
  378. auto toks = common_tokenize(vocab, el[0].get<std::string>(), false);
  379. for (auto tok : toks) {
  380. params.sampling.logit_bias.push_back({tok, bias});
  381. }
  382. }
  383. }
  384. }
  385. }
  386. }
  387. {
  388. params.antiprompt.clear();
  389. const auto & stop = data.find("stop");
  390. if (stop != data.end() && stop->is_array()) {
  391. for (const auto & word : *stop) {
  392. if (!word.empty()) {
  393. params.antiprompt.push_back(word);
  394. }
  395. }
  396. }
  397. }
  398. {
  399. const auto samplers = data.find("samplers");
  400. if (samplers != data.end()) {
  401. if (samplers->is_array()) {
  402. params.sampling.samplers = common_sampler_types_from_names(*samplers, false);
  403. } else if (samplers->is_string()){
  404. params.sampling.samplers = common_sampler_types_from_chars(samplers->get<std::string>());
  405. }
  406. } else {
  407. params.sampling.samplers = defaults.sampling.samplers;
  408. }
  409. }
  410. std::string model_name = params_base.model_alias.empty() ? DEFAULT_OAICOMPAT_MODEL : params_base.model_alias;
  411. params.oaicompat_model = json_value(data, "model", model_name);
  412. return params;
  413. }
  414. // utility function
  415. static std::unordered_set<int> get_list_id(const std::vector<server_task> & tasks) {
  416. std::unordered_set<int> ids(tasks.size());
  417. for (size_t i = 0; i < tasks.size(); i++) {
  418. ids.insert(tasks[i].id);
  419. }
  420. return ids;
  421. }
  422. };
  423. struct result_timings {
  424. int32_t prompt_n = -1;
  425. double prompt_ms;
  426. double prompt_per_token_ms;
  427. double prompt_per_second;
  428. int32_t predicted_n = -1;
  429. double predicted_ms;
  430. double predicted_per_token_ms;
  431. double predicted_per_second;
  432. // Optional speculative metrics - only included when > 0
  433. int32_t draft_n = 0;
  434. int32_t draft_n_accepted = 0;
  435. json to_json() const {
  436. json base = {
  437. {"prompt_n", prompt_n},
  438. {"prompt_ms", prompt_ms},
  439. {"prompt_per_token_ms", prompt_per_token_ms},
  440. {"prompt_per_second", prompt_per_second},
  441. {"predicted_n", predicted_n},
  442. {"predicted_ms", predicted_ms},
  443. {"predicted_per_token_ms", predicted_per_token_ms},
  444. {"predicted_per_second", predicted_per_second},
  445. };
  446. if (draft_n > 0) {
  447. base["draft_n"] = draft_n;
  448. base["draft_n_accepted"] = draft_n_accepted;
  449. }
  450. return base;
  451. }
  452. };
  453. struct server_task_result {
  454. int id = -1;
  455. int id_slot = -1;
  456. virtual bool is_error() {
  457. // only used by server_task_result_error
  458. return false;
  459. }
  460. virtual bool is_stop() {
  461. // only used by server_task_result_cmpl_*
  462. return false;
  463. }
  464. virtual int get_index() {
  465. return -1;
  466. }
  467. virtual json to_json() = 0;
  468. virtual ~server_task_result() = default;
  469. };
  470. // using shared_ptr for polymorphism of server_task_result
  471. using server_task_result_ptr = std::unique_ptr<server_task_result>;
  472. inline std::string stop_type_to_str(stop_type type) {
  473. switch (type) {
  474. case STOP_TYPE_EOS: return "eos";
  475. case STOP_TYPE_WORD: return "word";
  476. case STOP_TYPE_LIMIT: return "limit";
  477. default: return "none";
  478. }
  479. }
  480. struct completion_token_output {
  481. llama_token tok;
  482. float prob;
  483. std::string text_to_send;
  484. struct prob_info {
  485. llama_token tok;
  486. std::string txt;
  487. float prob;
  488. };
  489. std::vector<prob_info> probs;
  490. json to_json(bool post_sampling_probs) const {
  491. json probs_for_token = json::array();
  492. for (const auto & p : probs) {
  493. std::string txt(p.txt);
  494. txt.resize(validate_utf8(txt));
  495. probs_for_token.push_back(json {
  496. {"id", p.tok},
  497. {"token", txt},
  498. {"bytes", str_to_bytes(p.txt)},
  499. {
  500. post_sampling_probs ? "prob" : "logprob",
  501. post_sampling_probs ? p.prob : logarithm(p.prob)
  502. },
  503. });
  504. }
  505. return probs_for_token;
  506. }
  507. static json probs_vector_to_json(const std::vector<completion_token_output> & probs, bool post_sampling_probs) {
  508. json out = json::array();
  509. for (const auto & p : probs) {
  510. std::string txt(p.text_to_send);
  511. txt.resize(validate_utf8(txt));
  512. out.push_back(json {
  513. {"id", p.tok},
  514. {"token", txt},
  515. {"bytes", str_to_bytes(p.text_to_send)},
  516. {
  517. post_sampling_probs ? "prob" : "logprob",
  518. post_sampling_probs ? p.prob : logarithm(p.prob)
  519. },
  520. {
  521. post_sampling_probs ? "top_probs" : "top_logprobs",
  522. p.to_json(post_sampling_probs)
  523. },
  524. });
  525. }
  526. return out;
  527. }
  528. static float logarithm(float x) {
  529. // nlohmann::json converts -inf to null, so we need to prevent that
  530. return x == 0.0f ? std::numeric_limits<float>::lowest() : std::log(x);
  531. }
  532. static std::vector<unsigned char> str_to_bytes(const std::string & str) {
  533. std::vector<unsigned char> bytes;
  534. for (unsigned char c : str) {
  535. bytes.push_back(c);
  536. }
  537. return bytes;
  538. }
  539. };
  540. struct server_task_result_cmpl_final : server_task_result {
  541. int index = 0;
  542. std::string content;
  543. llama_tokens tokens;
  544. bool stream;
  545. result_timings timings;
  546. std::string prompt;
  547. bool truncated;
  548. int32_t n_decoded;
  549. int32_t n_prompt_tokens;
  550. int32_t n_tokens_cached;
  551. bool has_new_line;
  552. std::string stopping_word;
  553. stop_type stop = STOP_TYPE_NONE;
  554. bool post_sampling_probs;
  555. std::vector<completion_token_output> probs_output;
  556. std::vector<std::string> response_fields;
  557. slot_params generation_params;
  558. // OAI-compat fields
  559. bool verbose = false;
  560. oaicompat_type oaicompat = OAICOMPAT_TYPE_NONE;
  561. std::string oaicompat_model;
  562. std::string oaicompat_cmpl_id;
  563. common_chat_format oaicompat_chat_format = COMMON_CHAT_FORMAT_CONTENT_ONLY;
  564. virtual int get_index() override {
  565. return index;
  566. }
  567. virtual bool is_stop() override {
  568. return true; // in stream mode, final responses are considered stop
  569. }
  570. virtual json to_json() override {
  571. switch (oaicompat) {
  572. case OAICOMPAT_TYPE_NONE:
  573. return to_json_non_oaicompat();
  574. case OAICOMPAT_TYPE_COMPLETION:
  575. return to_json_oaicompat();
  576. case OAICOMPAT_TYPE_CHAT:
  577. return stream ? to_json_oaicompat_chat_stream() : to_json_oaicompat_chat();
  578. default:
  579. GGML_ASSERT(false && "Invalid oaicompat_type");
  580. }
  581. }
  582. json to_json_non_oaicompat() {
  583. json res = json {
  584. {"index", index},
  585. {"content", stream ? "" : content}, // in stream mode, content is already in last partial chunk
  586. {"tokens", stream ? llama_tokens {} : tokens},
  587. {"id_slot", id_slot},
  588. {"stop", true},
  589. {"model", oaicompat_model},
  590. {"tokens_predicted", n_decoded},
  591. {"tokens_evaluated", n_prompt_tokens},
  592. {"generation_settings", generation_params.to_json()},
  593. {"prompt", prompt},
  594. {"has_new_line", has_new_line},
  595. {"truncated", truncated},
  596. {"stop_type", stop_type_to_str(stop)},
  597. {"stopping_word", stopping_word},
  598. {"tokens_cached", n_tokens_cached},
  599. {"timings", timings.to_json()},
  600. };
  601. if (!stream && !probs_output.empty()) {
  602. res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs);
  603. }
  604. return response_fields.empty() ? res : json_get_nested_values(response_fields, res);
  605. }
  606. json to_json_oaicompat() {
  607. std::time_t t = std::time(0);
  608. json logprobs = json(nullptr); // OAI default to null
  609. if (!stream && probs_output.size() > 0) {
  610. logprobs = json{
  611. {"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
  612. };
  613. }
  614. json finish_reason = "length";
  615. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  616. finish_reason = "stop";
  617. }
  618. json res = json {
  619. {"choices", json::array({
  620. json{
  621. {"text", stream ? "" : content}, // in stream mode, content is already in last partial chunk
  622. {"index", index},
  623. {"logprobs", logprobs},
  624. {"finish_reason", finish_reason},
  625. }
  626. })},
  627. {"created", t},
  628. {"model", oaicompat_model},
  629. {"system_fingerprint", build_info},
  630. {"object", "text_completion"},
  631. {"usage", json {
  632. {"completion_tokens", n_decoded},
  633. {"prompt_tokens", n_prompt_tokens},
  634. {"total_tokens", n_decoded + n_prompt_tokens}
  635. }},
  636. {"id", oaicompat_cmpl_id}
  637. };
  638. // extra fields for debugging purposes
  639. if (verbose) {
  640. res["__verbose"] = to_json_non_oaicompat();
  641. }
  642. if (timings.prompt_n >= 0) {
  643. res.push_back({"timings", timings.to_json()});
  644. }
  645. return res;
  646. }
  647. json to_json_oaicompat_chat() {
  648. std::string finish_reason = "length";
  649. common_chat_msg msg;
  650. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  651. SRV_DBG("Parsing chat message: %s\n", content.c_str());
  652. msg = common_chat_parse(content, oaicompat_chat_format);
  653. finish_reason = msg.tool_calls.empty() ? "stop" : "tool_calls";
  654. } else {
  655. msg.content = content;
  656. }
  657. json message {
  658. {"role", "assistant"},
  659. };
  660. if (!msg.reasoning_content.empty()) {
  661. message["reasoning_content"] = msg.reasoning_content;
  662. }
  663. if (msg.content.empty() && !msg.tool_calls.empty()) {
  664. message["content"] = json();
  665. } else {
  666. message["content"] = msg.content;
  667. }
  668. if (!msg.tool_calls.empty()) {
  669. auto tool_calls = json::array();
  670. for (const auto & tc : msg.tool_calls) {
  671. tool_calls.push_back({
  672. {"type", "function"},
  673. {"function", {
  674. {"name", tc.name},
  675. {"arguments", tc.arguments},
  676. }},
  677. // Some templates generate and require an id (sometimes in a very specific format, e.g. Mistral Nemo).
  678. // We only generate a random id for the ones that don't generate one by themselves
  679. // (they also won't get to see it as their template likely doesn't use it, so it's all for the client)
  680. {"id", tc.id.empty() ? gen_tool_call_id() : tc.id},
  681. });
  682. }
  683. message["tool_calls"] = tool_calls;
  684. }
  685. json choice {
  686. {"finish_reason", finish_reason},
  687. {"index", 0},
  688. {"message", message},
  689. };
  690. if (!stream && probs_output.size() > 0) {
  691. choice["logprobs"] = json{
  692. {"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
  693. };
  694. }
  695. std::time_t t = std::time(0);
  696. json res = json {
  697. {"choices", json::array({choice})},
  698. {"created", t},
  699. {"model", oaicompat_model},
  700. {"system_fingerprint", build_info},
  701. {"object", "chat.completion"},
  702. {"usage", json {
  703. {"completion_tokens", n_decoded},
  704. {"prompt_tokens", n_prompt_tokens},
  705. {"total_tokens", n_decoded + n_prompt_tokens}
  706. }},
  707. {"id", oaicompat_cmpl_id}
  708. };
  709. // extra fields for debugging purposes
  710. if (verbose) {
  711. res["__verbose"] = to_json_non_oaicompat();
  712. }
  713. if (timings.prompt_n >= 0) {
  714. res.push_back({"timings", timings.to_json()});
  715. }
  716. return res;
  717. }
  718. json to_json_oaicompat_chat_stream() {
  719. std::time_t t = std::time(0);
  720. std::string finish_reason = "length";
  721. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  722. finish_reason = "stop";
  723. }
  724. json choice = json {
  725. {"finish_reason", finish_reason},
  726. {"index", 0},
  727. {"delta", json::object()}
  728. };
  729. json ret = json {
  730. {"choices", json::array({choice})},
  731. {"created", t},
  732. {"id", oaicompat_cmpl_id},
  733. {"model", oaicompat_model},
  734. {"system_fingerprint", build_info},
  735. {"object", "chat.completion.chunk"},
  736. {"usage", json {
  737. {"completion_tokens", n_decoded},
  738. {"prompt_tokens", n_prompt_tokens},
  739. {"total_tokens", n_decoded + n_prompt_tokens},
  740. }},
  741. };
  742. if (timings.prompt_n >= 0) {
  743. ret.push_back({"timings", timings.to_json()});
  744. }
  745. // extra fields for debugging purposes
  746. if (verbose) {
  747. ret["__verbose"] = to_json_non_oaicompat();
  748. }
  749. return ret;
  750. }
  751. };
  752. struct server_task_result_cmpl_partial : server_task_result {
  753. int index = 0;
  754. std::string content;
  755. llama_tokens tokens;
  756. int32_t n_decoded;
  757. int32_t n_prompt_tokens;
  758. bool post_sampling_probs;
  759. completion_token_output prob_output;
  760. result_timings timings;
  761. // OAI-compat fields
  762. bool verbose = false;
  763. oaicompat_type oaicompat = OAICOMPAT_TYPE_NONE;
  764. std::string oaicompat_model;
  765. std::string oaicompat_cmpl_id;
  766. virtual int get_index() override {
  767. return index;
  768. }
  769. virtual bool is_stop() override {
  770. return false; // in stream mode, partial responses are not considered stop
  771. }
  772. virtual json to_json() override {
  773. switch (oaicompat) {
  774. case OAICOMPAT_TYPE_NONE:
  775. return to_json_non_oaicompat();
  776. case OAICOMPAT_TYPE_COMPLETION:
  777. return to_json_oaicompat();
  778. case OAICOMPAT_TYPE_CHAT:
  779. return to_json_oaicompat_chat();
  780. default:
  781. GGML_ASSERT(false && "Invalid oaicompat_type");
  782. }
  783. }
  784. json to_json_non_oaicompat() {
  785. // non-OAI-compat JSON
  786. json res = json {
  787. {"index", index},
  788. {"content", content},
  789. {"tokens", tokens},
  790. {"stop", false},
  791. {"id_slot", id_slot},
  792. {"tokens_predicted", n_decoded},
  793. {"tokens_evaluated", n_prompt_tokens},
  794. };
  795. // populate the timings object when needed (usually for the last response or with timings_per_token enabled)
  796. if (timings.prompt_n > 0) {
  797. res.push_back({"timings", timings.to_json()});
  798. }
  799. if (!prob_output.probs.empty()) {
  800. res["completion_probabilities"] = completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs);
  801. }
  802. return res;
  803. }
  804. json to_json_oaicompat() {
  805. std::time_t t = std::time(0);
  806. json logprobs = json(nullptr); // OAI default to null
  807. if (prob_output.probs.size() > 0) {
  808. logprobs = json{
  809. {"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
  810. };
  811. }
  812. json res = json {
  813. {"choices", json::array({
  814. json{
  815. {"text", content},
  816. {"index", index},
  817. {"logprobs", logprobs},
  818. {"finish_reason", nullptr},
  819. }
  820. })},
  821. {"created", t},
  822. {"model", oaicompat_model},
  823. {"system_fingerprint", build_info},
  824. {"object", "text_completion"},
  825. {"id", oaicompat_cmpl_id}
  826. };
  827. // extra fields for debugging purposes
  828. if (verbose) {
  829. res["__verbose"] = to_json_non_oaicompat();
  830. }
  831. if (timings.prompt_n >= 0) {
  832. res.push_back({"timings", timings.to_json()});
  833. }
  834. return res;
  835. }
  836. json to_json_oaicompat_chat() {
  837. bool first = n_decoded == 0;
  838. std::time_t t = std::time(0);
  839. json choices;
  840. if (first) {
  841. if (content.empty()) {
  842. choices = json::array({json{{"finish_reason", nullptr},
  843. {"index", 0},
  844. {"delta", json{{"role", "assistant"}}}}});
  845. } else {
  846. // We have to send this as two updates to conform to openai behavior
  847. json initial_ret = json{{"choices", json::array({json{
  848. {"finish_reason", nullptr},
  849. {"index", 0},
  850. {"delta", json{
  851. {"role", "assistant"}
  852. }}}})},
  853. {"created", t},
  854. {"id", oaicompat_cmpl_id},
  855. {"model", oaicompat_model},
  856. {"object", "chat.completion.chunk"}};
  857. json second_ret = json{
  858. {"choices", json::array({json{{"finish_reason", nullptr},
  859. {"index", 0},
  860. {"delta", json {
  861. {"content", content}}}
  862. }})},
  863. {"created", t},
  864. {"id", oaicompat_cmpl_id},
  865. {"model", oaicompat_model},
  866. {"object", "chat.completion.chunk"}};
  867. return std::vector<json>({initial_ret, second_ret});
  868. }
  869. } else {
  870. choices = json::array({json{
  871. {"finish_reason", nullptr},
  872. {"index", 0},
  873. {"delta",
  874. json {
  875. {"content", content},
  876. }},
  877. }});
  878. }
  879. GGML_ASSERT(choices.size() >= 1);
  880. if (prob_output.probs.size() > 0) {
  881. choices[0]["logprobs"] = json{
  882. {"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
  883. };
  884. }
  885. json ret = json {
  886. {"choices", choices},
  887. {"created", t},
  888. {"id", oaicompat_cmpl_id},
  889. {"model", oaicompat_model},
  890. {"system_fingerprint", build_info},
  891. {"object", "chat.completion.chunk"}
  892. };
  893. if (timings.prompt_n >= 0) {
  894. ret.push_back({"timings", timings.to_json()});
  895. }
  896. return std::vector<json>({ret});
  897. }
  898. };
  899. struct server_task_result_embd : server_task_result {
  900. int index = 0;
  901. std::vector<std::vector<float>> embedding;
  902. int32_t n_tokens;
  903. // OAI-compat fields
  904. oaicompat_type oaicompat = OAICOMPAT_TYPE_NONE;
  905. virtual int get_index() override {
  906. return index;
  907. }
  908. virtual json to_json() override {
  909. return oaicompat == OAICOMPAT_TYPE_EMBEDDING
  910. ? to_json_oaicompat()
  911. : to_json_non_oaicompat();
  912. }
  913. json to_json_non_oaicompat() {
  914. return json {
  915. {"index", index},
  916. {"embedding", embedding},
  917. };
  918. }
  919. json to_json_oaicompat() {
  920. return json {
  921. {"index", index},
  922. {"embedding", embedding[0]},
  923. {"tokens_evaluated", n_tokens},
  924. };
  925. }
  926. };
  927. struct server_task_result_rerank : server_task_result {
  928. int index = 0;
  929. float score = -1e6;
  930. int32_t n_tokens;
  931. virtual int get_index() override {
  932. return index;
  933. }
  934. virtual json to_json() override {
  935. return json {
  936. {"index", index},
  937. {"score", score},
  938. {"tokens_evaluated", n_tokens},
  939. };
  940. }
  941. };
  942. // this function maybe used outside of server_task_result_error
  943. static json format_error_response(const std::string & message, const enum error_type type) {
  944. std::string type_str;
  945. int code = 500;
  946. switch (type) {
  947. case ERROR_TYPE_INVALID_REQUEST:
  948. type_str = "invalid_request_error";
  949. code = 400;
  950. break;
  951. case ERROR_TYPE_AUTHENTICATION:
  952. type_str = "authentication_error";
  953. code = 401;
  954. break;
  955. case ERROR_TYPE_NOT_FOUND:
  956. type_str = "not_found_error";
  957. code = 404;
  958. break;
  959. case ERROR_TYPE_SERVER:
  960. type_str = "server_error";
  961. code = 500;
  962. break;
  963. case ERROR_TYPE_PERMISSION:
  964. type_str = "permission_error";
  965. code = 403;
  966. break;
  967. case ERROR_TYPE_NOT_SUPPORTED:
  968. type_str = "not_supported_error";
  969. code = 501;
  970. break;
  971. case ERROR_TYPE_UNAVAILABLE:
  972. type_str = "unavailable_error";
  973. code = 503;
  974. break;
  975. }
  976. return json {
  977. {"code", code},
  978. {"message", message},
  979. {"type", type_str},
  980. };
  981. }
  982. struct server_task_result_error : server_task_result {
  983. int index = 0;
  984. error_type err_type = ERROR_TYPE_SERVER;
  985. std::string err_msg;
  986. virtual bool is_error() override {
  987. return true;
  988. }
  989. virtual json to_json() override {
  990. return format_error_response(err_msg, err_type);
  991. }
  992. };
  993. struct server_task_result_metrics : server_task_result {
  994. int n_idle_slots;
  995. int n_processing_slots;
  996. int n_tasks_deferred;
  997. int64_t t_start;
  998. // TODO: somehow reuse server_metrics in the future, instead of duplicating the fields
  999. uint64_t n_prompt_tokens_processed_total = 0;
  1000. uint64_t t_prompt_processing_total = 0;
  1001. uint64_t n_tokens_predicted_total = 0;
  1002. uint64_t t_tokens_generation_total = 0;
  1003. uint64_t n_prompt_tokens_processed = 0;
  1004. uint64_t t_prompt_processing = 0;
  1005. uint64_t n_tokens_predicted = 0;
  1006. uint64_t t_tokens_generation = 0;
  1007. uint64_t n_decode_total = 0;
  1008. uint64_t n_busy_slots_total = 0;
  1009. // while we can also use std::vector<server_slot> this requires copying the slot object which can be quite messy
  1010. // therefore, we use json to temporarily store the slot.to_json() result
  1011. json slots_data = json::array();
  1012. virtual json to_json() override {
  1013. return json {
  1014. { "idle", n_idle_slots },
  1015. { "processing", n_processing_slots },
  1016. { "deferred", n_tasks_deferred },
  1017. { "t_start", t_start },
  1018. { "n_prompt_tokens_processed_total", n_prompt_tokens_processed_total },
  1019. { "t_tokens_generation_total", t_tokens_generation_total },
  1020. { "n_tokens_predicted_total", n_tokens_predicted_total },
  1021. { "t_prompt_processing_total", t_prompt_processing_total },
  1022. { "n_prompt_tokens_processed", n_prompt_tokens_processed },
  1023. { "t_prompt_processing", t_prompt_processing },
  1024. { "n_tokens_predicted", n_tokens_predicted },
  1025. { "t_tokens_generation", t_tokens_generation },
  1026. { "n_decode_total", n_decode_total },
  1027. { "n_busy_slots_total", n_busy_slots_total },
  1028. { "slots", slots_data },
  1029. };
  1030. }
  1031. };
  1032. struct server_task_result_slot_save_load : server_task_result {
  1033. std::string filename;
  1034. bool is_save; // true = save, false = load
  1035. size_t n_tokens;
  1036. size_t n_bytes;
  1037. double t_ms;
  1038. virtual json to_json() override {
  1039. if (is_save) {
  1040. return json {
  1041. { "id_slot", id_slot },
  1042. { "filename", filename },
  1043. { "n_saved", n_tokens },
  1044. { "n_written", n_bytes },
  1045. { "timings", {
  1046. { "save_ms", t_ms }
  1047. }},
  1048. };
  1049. } else {
  1050. return json {
  1051. { "id_slot", id_slot },
  1052. { "filename", filename },
  1053. { "n_restored", n_tokens },
  1054. { "n_read", n_bytes },
  1055. { "timings", {
  1056. { "restore_ms", t_ms }
  1057. }},
  1058. };
  1059. }
  1060. }
  1061. };
  1062. struct server_task_result_slot_erase : server_task_result {
  1063. size_t n_erased;
  1064. virtual json to_json() override {
  1065. return json {
  1066. { "id_slot", id_slot },
  1067. { "n_erased", n_erased },
  1068. };
  1069. }
  1070. };
  1071. struct server_task_result_apply_lora : server_task_result {
  1072. virtual json to_json() override {
  1073. return json {{ "success", true }};
  1074. }
  1075. };
  1076. struct server_slot {
  1077. int id;
  1078. int id_task = -1;
  1079. // only used for completion/embedding/infill/rerank
  1080. server_task_type task_type = SERVER_TASK_TYPE_COMPLETION;
  1081. llama_batch batch_spec = {};
  1082. llama_context * ctx = nullptr;
  1083. llama_context * ctx_dft = nullptr;
  1084. // multimodal
  1085. mtmd_context * mctx = nullptr;
  1086. common_speculative * spec = nullptr;
  1087. std::vector<common_adapter_lora_info> lora;
  1088. // the index relative to completion multi-task request
  1089. size_t index = 0;
  1090. struct slot_params params;
  1091. slot_state state = SLOT_STATE_IDLE;
  1092. // used to determine the slot that has been used the longest
  1093. int64_t t_last_used = -1;
  1094. // generation props
  1095. int32_t n_ctx = 0; // context size per slot
  1096. int32_t n_past = 0;
  1097. int32_t n_decoded = 0;
  1098. int32_t n_remaining = -1;
  1099. int32_t i_batch = -1;
  1100. int32_t n_predict = -1; // TODO: disambiguate from params.n_predict
  1101. // n_prompt_tokens may not be equal to prompt_tokens.size(), because prompt maybe truncated
  1102. int32_t n_prompt_tokens = 0;
  1103. int32_t n_prompt_tokens_processed = 0;
  1104. // input prompt tokens
  1105. server_tokens prompt_tokens;
  1106. size_t last_nl_pos = 0;
  1107. std::string generated_text;
  1108. llama_tokens generated_tokens;
  1109. server_tokens cache_tokens;
  1110. std::vector<completion_token_output> generated_token_probs;
  1111. bool has_next_token = true;
  1112. bool has_new_line = false;
  1113. bool truncated = false;
  1114. stop_type stop;
  1115. std::string stopping_word;
  1116. // sampling
  1117. json json_schema;
  1118. struct common_sampler * smpl = nullptr;
  1119. llama_token sampled;
  1120. common_chat_format chat_format = COMMON_CHAT_FORMAT_CONTENT_ONLY;
  1121. // stats
  1122. size_t n_sent_text = 0; // number of sent text character
  1123. int64_t t_start_process_prompt;
  1124. int64_t t_start_generation;
  1125. double t_prompt_processing; // ms
  1126. double t_token_generation; // ms
  1127. std::function<void(int)> callback_on_release;
  1128. // Speculative decoding stats
  1129. int32_t n_draft_total = 0; // Total draft tokens generated
  1130. int32_t n_draft_accepted = 0; // Draft tokens actually accepted
  1131. void reset() {
  1132. SLT_DBG(*this, "%s", "\n");
  1133. n_prompt_tokens = 0;
  1134. last_nl_pos = 0;
  1135. generated_text = "";
  1136. has_new_line = false;
  1137. truncated = false;
  1138. stop = STOP_TYPE_NONE;
  1139. stopping_word = "";
  1140. n_past = 0;
  1141. n_sent_text = 0;
  1142. task_type = SERVER_TASK_TYPE_COMPLETION;
  1143. generated_tokens.clear();
  1144. generated_token_probs.clear();
  1145. // clear speculative decoding stats
  1146. n_draft_total = 0;
  1147. n_draft_accepted = 0;
  1148. }
  1149. bool is_non_causal() const {
  1150. return task_type == SERVER_TASK_TYPE_EMBEDDING || task_type == SERVER_TASK_TYPE_RERANK;
  1151. }
  1152. bool can_batch_with(server_slot & other_slot) const {
  1153. return is_non_causal() == other_slot.is_non_causal()
  1154. && are_lora_equal(lora, other_slot.lora);
  1155. }
  1156. bool has_budget(const common_params & global_params) {
  1157. if (params.n_predict == -1 && global_params.n_predict == -1) {
  1158. return true; // limitless
  1159. }
  1160. n_remaining = -1;
  1161. if (params.n_predict != -1) {
  1162. n_remaining = params.n_predict - n_decoded;
  1163. } else if (global_params.n_predict != -1) {
  1164. n_remaining = global_params.n_predict - n_decoded;
  1165. }
  1166. return n_remaining > 0; // no budget
  1167. }
  1168. bool is_processing() const {
  1169. return state != SLOT_STATE_IDLE;
  1170. }
  1171. bool can_speculate() const {
  1172. return ctx_dft && params.speculative.n_max > 0 && params.cache_prompt;
  1173. }
  1174. void add_token(const completion_token_output & token) {
  1175. if (!is_processing()) {
  1176. SLT_WRN(*this, "%s", "slot is not processing\n");
  1177. return;
  1178. }
  1179. generated_token_probs.push_back(token);
  1180. }
  1181. void release() {
  1182. if (is_processing()) {
  1183. SLT_INF(*this, "stop processing: n_past = %d, truncated = %d\n", n_past, truncated);
  1184. t_last_used = ggml_time_us();
  1185. t_token_generation = (ggml_time_us() - t_start_generation) / 1e3;
  1186. state = SLOT_STATE_IDLE;
  1187. callback_on_release(id);
  1188. }
  1189. }
  1190. result_timings get_timings() const {
  1191. result_timings timings;
  1192. timings.prompt_n = n_prompt_tokens_processed;
  1193. timings.prompt_ms = t_prompt_processing;
  1194. timings.prompt_per_token_ms = t_prompt_processing / n_prompt_tokens_processed;
  1195. timings.prompt_per_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  1196. timings.predicted_n = n_decoded;
  1197. timings.predicted_ms = t_token_generation;
  1198. timings.predicted_per_token_ms = t_token_generation / n_decoded;
  1199. timings.predicted_per_second = 1e3 / t_token_generation * n_decoded;
  1200. // Add speculative metrics
  1201. if (n_draft_total > 0) {
  1202. timings.draft_n = n_draft_total;
  1203. timings.draft_n_accepted = n_draft_accepted;
  1204. }
  1205. return timings;
  1206. }
  1207. size_t find_stopping_strings(const std::string & text, const size_t last_token_size, bool is_full_stop) {
  1208. size_t stop_pos = std::string::npos;
  1209. for (const std::string & word : params.antiprompt) {
  1210. size_t pos;
  1211. if (is_full_stop) {
  1212. const size_t tmp = word.size() + last_token_size;
  1213. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  1214. pos = text.find(word, from_pos);
  1215. } else {
  1216. // otherwise, partial stop
  1217. pos = string_find_partial_stop(text, word);
  1218. }
  1219. if (pos != std::string::npos && (stop_pos == std::string::npos || pos < stop_pos)) {
  1220. if (is_full_stop) {
  1221. stop = STOP_TYPE_WORD;
  1222. stopping_word = word;
  1223. has_next_token = false;
  1224. }
  1225. stop_pos = pos;
  1226. }
  1227. }
  1228. return stop_pos;
  1229. }
  1230. void print_timings() const {
  1231. const double t_prompt = t_prompt_processing / n_prompt_tokens_processed;
  1232. const double n_prompt_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  1233. const double t_gen = t_token_generation / n_decoded;
  1234. const double n_gen_second = 1e3 / t_token_generation * n_decoded;
  1235. SLT_INF(*this,
  1236. "\n"
  1237. "prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n"
  1238. " eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n"
  1239. " total time = %10.2f ms / %5d tokens\n",
  1240. t_prompt_processing, n_prompt_tokens_processed, t_prompt, n_prompt_second,
  1241. t_token_generation, n_decoded, t_gen, n_gen_second,
  1242. t_prompt_processing + t_token_generation, n_prompt_tokens_processed + n_decoded);
  1243. if (n_draft_total > 0) {
  1244. const float draft_ratio = (float) n_draft_accepted / n_draft_total;
  1245. SLT_INF(*this,
  1246. "\n"
  1247. "draft acceptance rate = %0.5f (%5d accepted / %5d generated)\n",
  1248. draft_ratio, n_draft_accepted, n_draft_total
  1249. );
  1250. }
  1251. }
  1252. json to_json() const {
  1253. return json {
  1254. {"id", id},
  1255. {"id_task", id_task},
  1256. {"n_ctx", n_ctx},
  1257. {"speculative", can_speculate()},
  1258. {"is_processing", is_processing()},
  1259. {"non_causal", is_non_causal()},
  1260. {"params", params.to_json()},
  1261. {"prompt", prompt_tokens.detokenize(ctx, true)},
  1262. {"next_token",
  1263. {
  1264. {"has_next_token", has_next_token},
  1265. {"has_new_line", has_new_line},
  1266. {"n_remain", n_remaining},
  1267. {"n_decoded", n_decoded},
  1268. {"stopping_word", stopping_word},
  1269. }
  1270. },
  1271. };
  1272. }
  1273. };
  1274. struct server_metrics {
  1275. int64_t t_start = 0;
  1276. uint64_t n_prompt_tokens_processed_total = 0;
  1277. uint64_t t_prompt_processing_total = 0;
  1278. uint64_t n_tokens_predicted_total = 0;
  1279. uint64_t t_tokens_generation_total = 0;
  1280. uint64_t n_prompt_tokens_processed = 0;
  1281. uint64_t t_prompt_processing = 0;
  1282. uint64_t n_tokens_predicted = 0;
  1283. uint64_t t_tokens_generation = 0;
  1284. uint64_t n_decode_total = 0;
  1285. uint64_t n_busy_slots_total = 0;
  1286. void init() {
  1287. t_start = ggml_time_us();
  1288. }
  1289. void on_prompt_eval(const server_slot & slot) {
  1290. n_prompt_tokens_processed_total += slot.n_prompt_tokens_processed;
  1291. n_prompt_tokens_processed += slot.n_prompt_tokens_processed;
  1292. t_prompt_processing += slot.t_prompt_processing;
  1293. t_prompt_processing_total += slot.t_prompt_processing;
  1294. }
  1295. void on_prediction(const server_slot & slot) {
  1296. n_tokens_predicted_total += slot.n_decoded;
  1297. n_tokens_predicted += slot.n_decoded;
  1298. t_tokens_generation += slot.t_token_generation;
  1299. t_tokens_generation_total += slot.t_token_generation;
  1300. }
  1301. void on_decoded(const std::vector<server_slot> & slots) {
  1302. n_decode_total++;
  1303. for (const auto & slot : slots) {
  1304. if (slot.is_processing()) {
  1305. n_busy_slots_total++;
  1306. }
  1307. }
  1308. }
  1309. void reset_bucket() {
  1310. n_prompt_tokens_processed = 0;
  1311. t_prompt_processing = 0;
  1312. n_tokens_predicted = 0;
  1313. t_tokens_generation = 0;
  1314. }
  1315. };
  1316. struct server_queue {
  1317. int id = 0;
  1318. bool running;
  1319. // queues
  1320. std::deque<server_task> queue_tasks;
  1321. std::deque<server_task> queue_tasks_deferred;
  1322. std::mutex mutex_tasks;
  1323. std::condition_variable condition_tasks;
  1324. // callback functions
  1325. std::function<void(server_task &&)> callback_new_task;
  1326. std::function<void(void)> callback_update_slots;
  1327. // Add a new task to the end of the queue
  1328. int post(server_task && task, bool front = false) {
  1329. std::unique_lock<std::mutex> lock(mutex_tasks);
  1330. GGML_ASSERT(task.id != -1);
  1331. // if this is cancel task make sure to clean up pending tasks
  1332. if (task.type == SERVER_TASK_TYPE_CANCEL) {
  1333. cleanup_pending_task(task.id_target);
  1334. }
  1335. const int task_id = task.id;
  1336. QUE_DBG("new task, id = %d, front = %d\n", task_id, front);
  1337. if (front) {
  1338. queue_tasks.push_front(std::move(task));
  1339. } else {
  1340. queue_tasks.push_back(std::move(task));
  1341. }
  1342. condition_tasks.notify_one();
  1343. return task_id;
  1344. }
  1345. // multi-task version of post()
  1346. int post(std::vector<server_task> && tasks, bool front = false) {
  1347. std::unique_lock<std::mutex> lock(mutex_tasks);
  1348. for (auto & task : tasks) {
  1349. if (task.id == -1) {
  1350. task.id = id++;
  1351. }
  1352. // if this is cancel task make sure to clean up pending tasks
  1353. if (task.type == SERVER_TASK_TYPE_CANCEL) {
  1354. cleanup_pending_task(task.id_target);
  1355. }
  1356. QUE_DBG("new task, id = %d/%d, front = %d\n", task.id, (int) tasks.size(), front);
  1357. if (front) {
  1358. queue_tasks.push_front(std::move(task));
  1359. } else {
  1360. queue_tasks.push_back(std::move(task));
  1361. }
  1362. }
  1363. condition_tasks.notify_one();
  1364. return 0;
  1365. }
  1366. // Add a new task, but defer until one slot is available
  1367. void defer(server_task && task) {
  1368. std::unique_lock<std::mutex> lock(mutex_tasks);
  1369. QUE_DBG("defer task, id = %d\n", task.id);
  1370. queue_tasks_deferred.push_back(std::move(task));
  1371. condition_tasks.notify_one();
  1372. }
  1373. // Get the next id for creating a new task
  1374. int get_new_id() {
  1375. std::unique_lock<std::mutex> lock(mutex_tasks);
  1376. int new_id = id++;
  1377. return new_id;
  1378. }
  1379. // Register function to process a new task
  1380. void on_new_task(std::function<void(server_task &&)> callback) {
  1381. callback_new_task = std::move(callback);
  1382. }
  1383. // Register the function to be called when all slots data is ready to be processed
  1384. void on_update_slots(std::function<void(void)> callback) {
  1385. callback_update_slots = std::move(callback);
  1386. }
  1387. // Call when the state of one slot is changed, it will move one task from deferred to main queue
  1388. void pop_deferred_task() {
  1389. std::unique_lock<std::mutex> lock(mutex_tasks);
  1390. if (!queue_tasks_deferred.empty()) {
  1391. queue_tasks.emplace_back(std::move(queue_tasks_deferred.front()));
  1392. queue_tasks_deferred.pop_front();
  1393. }
  1394. condition_tasks.notify_one();
  1395. }
  1396. // end the start_loop routine
  1397. void terminate() {
  1398. std::unique_lock<std::mutex> lock(mutex_tasks);
  1399. running = false;
  1400. condition_tasks.notify_all();
  1401. }
  1402. /**
  1403. * Main loop consists of these steps:
  1404. * - Wait until a new task arrives
  1405. * - Process the task (i.e. maybe copy data into slot)
  1406. * - Check if multitask is finished
  1407. * - Update all slots
  1408. */
  1409. void start_loop() {
  1410. running = true;
  1411. while (true) {
  1412. QUE_DBG("%s", "processing new tasks\n");
  1413. while (true) {
  1414. std::unique_lock<std::mutex> lock(mutex_tasks);
  1415. if (!running) {
  1416. QUE_DBG("%s", "terminate\n");
  1417. return;
  1418. }
  1419. if (queue_tasks.empty()) {
  1420. lock.unlock();
  1421. break;
  1422. }
  1423. server_task task = std::move(queue_tasks.front());
  1424. queue_tasks.pop_front();
  1425. lock.unlock();
  1426. QUE_DBG("processing task, id = %d\n", task.id);
  1427. callback_new_task(std::move(task));
  1428. }
  1429. // all tasks in the current loop is processed, slots data is now ready
  1430. QUE_DBG("%s", "update slots\n");
  1431. callback_update_slots();
  1432. QUE_DBG("%s", "waiting for new tasks\n");
  1433. {
  1434. std::unique_lock<std::mutex> lock(mutex_tasks);
  1435. if (!running) {
  1436. QUE_DBG("%s", "terminate\n");
  1437. return;
  1438. }
  1439. if (queue_tasks.empty()) {
  1440. condition_tasks.wait(lock, [&]{
  1441. return (!queue_tasks.empty() || !running);
  1442. });
  1443. }
  1444. }
  1445. }
  1446. }
  1447. private:
  1448. void cleanup_pending_task(int id_target) {
  1449. // no need lock because this is called exclusively by post()
  1450. auto rm_func = [id_target](const server_task & task) {
  1451. return task.id_target == id_target;
  1452. };
  1453. queue_tasks.erase(
  1454. std::remove_if(queue_tasks.begin(), queue_tasks.end(), rm_func),
  1455. queue_tasks.end());
  1456. queue_tasks_deferred.erase(
  1457. std::remove_if(queue_tasks_deferred.begin(), queue_tasks_deferred.end(), rm_func),
  1458. queue_tasks_deferred.end());
  1459. }
  1460. };
  1461. struct server_response {
  1462. bool running = true;
  1463. // for keeping track of all tasks waiting for the result
  1464. std::unordered_set<int> waiting_task_ids;
  1465. // the main result queue (using ptr for polymorphism)
  1466. std::vector<server_task_result_ptr> queue_results;
  1467. std::mutex mutex_results;
  1468. std::condition_variable condition_results;
  1469. // add the id_task to the list of tasks waiting for response
  1470. void add_waiting_task_id(int id_task) {
  1471. SRV_DBG("add task %d to waiting list. current waiting = %d (before add)\n", id_task, (int) waiting_task_ids.size());
  1472. std::unique_lock<std::mutex> lock(mutex_results);
  1473. waiting_task_ids.insert(id_task);
  1474. }
  1475. void add_waiting_tasks(const std::vector<server_task> & tasks) {
  1476. std::unique_lock<std::mutex> lock(mutex_results);
  1477. for (const auto & task : tasks) {
  1478. SRV_DBG("add task %d to waiting list. current waiting = %d (before add)\n", task.id, (int) waiting_task_ids.size());
  1479. waiting_task_ids.insert(task.id);
  1480. }
  1481. }
  1482. // when the request is finished, we can remove task associated with it
  1483. void remove_waiting_task_id(int id_task) {
  1484. SRV_DBG("remove task %d from waiting list. current waiting = %d (before remove)\n", id_task, (int) waiting_task_ids.size());
  1485. std::unique_lock<std::mutex> lock(mutex_results);
  1486. waiting_task_ids.erase(id_task);
  1487. // make sure to clean up all pending results
  1488. queue_results.erase(
  1489. std::remove_if(queue_results.begin(), queue_results.end(), [id_task](const server_task_result_ptr & res) {
  1490. return res->id == id_task;
  1491. }),
  1492. queue_results.end());
  1493. }
  1494. void remove_waiting_task_ids(const std::unordered_set<int> & id_tasks) {
  1495. std::unique_lock<std::mutex> lock(mutex_results);
  1496. for (const auto & id_task : id_tasks) {
  1497. SRV_DBG("remove task %d from waiting list. current waiting = %d (before remove)\n", id_task, (int) waiting_task_ids.size());
  1498. waiting_task_ids.erase(id_task);
  1499. }
  1500. }
  1501. // This function blocks the thread until there is a response for one of the id_tasks
  1502. server_task_result_ptr recv(const std::unordered_set<int> & id_tasks) {
  1503. while (true) {
  1504. std::unique_lock<std::mutex> lock(mutex_results);
  1505. condition_results.wait(lock, [&]{
  1506. if (!running) {
  1507. SRV_DBG("%s : queue result stop\n", __func__);
  1508. std::terminate(); // we cannot return here since the caller is HTTP code
  1509. }
  1510. return !queue_results.empty();
  1511. });
  1512. for (size_t i = 0; i < queue_results.size(); i++) {
  1513. if (id_tasks.find(queue_results[i]->id) != id_tasks.end()) {
  1514. server_task_result_ptr res = std::move(queue_results[i]);
  1515. queue_results.erase(queue_results.begin() + i);
  1516. return res;
  1517. }
  1518. }
  1519. }
  1520. // should never reach here
  1521. }
  1522. // same as recv(), but have timeout in seconds
  1523. // if timeout is reached, nullptr is returned
  1524. server_task_result_ptr recv_with_timeout(const std::unordered_set<int> & id_tasks, int timeout) {
  1525. while (true) {
  1526. std::unique_lock<std::mutex> lock(mutex_results);
  1527. for (int i = 0; i < (int) queue_results.size(); i++) {
  1528. if (id_tasks.find(queue_results[i]->id) != id_tasks.end()) {
  1529. server_task_result_ptr res = std::move(queue_results[i]);
  1530. queue_results.erase(queue_results.begin() + i);
  1531. return res;
  1532. }
  1533. }
  1534. std::cv_status cr_res = condition_results.wait_for(lock, std::chrono::seconds(timeout));
  1535. if (!running) {
  1536. SRV_DBG("%s : queue result stop\n", __func__);
  1537. std::terminate(); // we cannot return here since the caller is HTTP code
  1538. }
  1539. if (cr_res == std::cv_status::timeout) {
  1540. return nullptr;
  1541. }
  1542. }
  1543. // should never reach here
  1544. }
  1545. // single-task version of recv()
  1546. server_task_result_ptr recv(int id_task) {
  1547. std::unordered_set<int> id_tasks = {id_task};
  1548. return recv(id_tasks);
  1549. }
  1550. // Send a new result to a waiting id_task
  1551. void send(server_task_result_ptr && result) {
  1552. SRV_DBG("sending result for task id = %d\n", result->id);
  1553. std::unique_lock<std::mutex> lock(mutex_results);
  1554. for (const auto & id_task : waiting_task_ids) {
  1555. if (result->id == id_task) {
  1556. SRV_DBG("task id = %d pushed to result queue\n", result->id);
  1557. queue_results.emplace_back(std::move(result));
  1558. condition_results.notify_all();
  1559. return;
  1560. }
  1561. }
  1562. }
  1563. // terminate the waiting loop
  1564. void terminate() {
  1565. running = false;
  1566. condition_results.notify_all();
  1567. }
  1568. };
  1569. struct server_context {
  1570. common_params params_base;
  1571. // note: keep these alive - they determine the lifetime of the model, context, etc.
  1572. common_init_result llama_init;
  1573. common_init_result llama_init_dft;
  1574. llama_model * model = nullptr;
  1575. llama_context * ctx = nullptr;
  1576. // multimodal
  1577. mtmd_context * mctx = nullptr;
  1578. const llama_vocab * vocab = nullptr;
  1579. llama_model * model_dft = nullptr;
  1580. llama_context_params cparams_dft;
  1581. llama_batch batch {};
  1582. bool clean_kv_cache = true;
  1583. bool add_bos_token = true;
  1584. bool has_eos_token = false;
  1585. int32_t n_ctx; // total context for all clients / slots
  1586. // slots / clients
  1587. std::vector<server_slot> slots;
  1588. json default_generation_settings_for_props;
  1589. server_queue queue_tasks;
  1590. server_response queue_results;
  1591. server_metrics metrics;
  1592. // Necessary similarity of prompt for slot selection
  1593. float slot_prompt_similarity = 0.0f;
  1594. common_chat_templates_ptr chat_templates;
  1595. ~server_context() {
  1596. mtmd_free(mctx);
  1597. // Clear any sampling context
  1598. for (server_slot & slot : slots) {
  1599. common_sampler_free(slot.smpl);
  1600. slot.smpl = nullptr;
  1601. llama_free(slot.ctx_dft);
  1602. slot.ctx_dft = nullptr;
  1603. common_speculative_free(slot.spec);
  1604. slot.spec = nullptr;
  1605. llama_batch_free(slot.batch_spec);
  1606. }
  1607. llama_batch_free(batch);
  1608. }
  1609. bool load_model(const common_params & params) {
  1610. SRV_INF("loading model '%s'\n", params.model.path.c_str());
  1611. params_base = params;
  1612. llama_init = common_init_from_params(params_base);
  1613. model = llama_init.model.get();
  1614. ctx = llama_init.context.get();
  1615. if (model == nullptr) {
  1616. SRV_ERR("failed to load model, '%s'\n", params_base.model.path.c_str());
  1617. return false;
  1618. }
  1619. vocab = llama_model_get_vocab(model);
  1620. n_ctx = llama_n_ctx(ctx);
  1621. add_bos_token = llama_vocab_get_add_bos(vocab);
  1622. has_eos_token = llama_vocab_eos(vocab) != LLAMA_TOKEN_NULL;
  1623. if (!params_base.speculative.model.path.empty() || !params_base.speculative.model.hf_repo.empty()) {
  1624. SRV_INF("loading draft model '%s'\n", params_base.speculative.model.path.c_str());
  1625. auto params_dft = params_base;
  1626. params_dft.devices = params_base.speculative.devices;
  1627. params_dft.model = params_base.speculative.model;
  1628. params_dft.n_ctx = params_base.speculative.n_ctx == 0 ? params_base.n_ctx / params_base.n_parallel : params_base.speculative.n_ctx;
  1629. params_dft.n_gpu_layers = params_base.speculative.n_gpu_layers;
  1630. params_dft.n_parallel = 1;
  1631. // force F16 KV cache for the draft model for extra performance
  1632. params_dft.cache_type_k = GGML_TYPE_F16;
  1633. params_dft.cache_type_v = GGML_TYPE_F16;
  1634. llama_init_dft = common_init_from_params(params_dft);
  1635. model_dft = llama_init_dft.model.get();
  1636. if (model_dft == nullptr) {
  1637. SRV_ERR("failed to load draft model, '%s'\n", params_base.speculative.model.path.c_str());
  1638. return false;
  1639. }
  1640. if (!common_speculative_are_compatible(ctx, llama_init_dft.context.get())) {
  1641. SRV_ERR("the draft model '%s' is not compatible with the target model '%s'\n", params_base.speculative.model.path.c_str(), params_base.model.path.c_str());
  1642. return false;
  1643. }
  1644. const int n_ctx_dft = llama_n_ctx(llama_init_dft.context.get());
  1645. cparams_dft = common_context_params_to_llama(params_dft);
  1646. cparams_dft.n_batch = n_ctx_dft;
  1647. // the context is not needed - we will create one for each slot
  1648. llama_init_dft.context.reset();
  1649. }
  1650. chat_templates = common_chat_templates_init(model, params_base.chat_template);
  1651. try {
  1652. common_chat_format_example(chat_templates.get(), params.use_jinja);
  1653. } catch (const std::exception & e) {
  1654. SRV_WRN("%s: Chat template parsing error: %s\n", __func__, e.what());
  1655. SRV_WRN("%s: The chat template that comes with this model is not yet supported, falling back to chatml. This may cause the model to output suboptimal responses\n", __func__);
  1656. chat_templates = common_chat_templates_init(model, "chatml");
  1657. }
  1658. std::string & mmproj_path = params_base.mmproj.path;
  1659. if (!mmproj_path.empty()) {
  1660. mtmd_context_params mparams = mtmd_context_params_default();
  1661. mparams.use_gpu = params_base.mmproj_use_gpu;
  1662. mparams.print_timings = false;
  1663. mparams.n_threads = params_base.cpuparams.n_threads;
  1664. mparams.verbosity = params_base.verbosity > 0 ? GGML_LOG_LEVEL_DEBUG : GGML_LOG_LEVEL_INFO;
  1665. mctx = mtmd_init_from_file(mmproj_path.c_str(), model, mparams);
  1666. if (mctx == nullptr) {
  1667. SRV_ERR("failed to load multimodal model, '%s'\n", mmproj_path.c_str());
  1668. return false;
  1669. }
  1670. SRV_INF("loaded multimodal model, '%s'\n", mmproj_path.c_str());
  1671. if (params_base.ctx_shift) {
  1672. params_base.ctx_shift = false;
  1673. SRV_WRN("%s\n", "ctx_shift is not supported by multimodal, it will be disabled");
  1674. }
  1675. if (params_base.n_cache_reuse) {
  1676. params_base.n_cache_reuse = 0;
  1677. SRV_WRN("%s\n", "cache_reuse is not supported by multimodal, it will be disabled");
  1678. }
  1679. if (!params_base.speculative.model.path.empty()) {
  1680. SRV_ERR("%s\n", "err: speculative decode is not supported by multimodal");
  1681. return false;
  1682. }
  1683. }
  1684. if (!llama_kv_self_can_shift(ctx)) {
  1685. if (params_base.ctx_shift) {
  1686. params_base.ctx_shift = false;
  1687. SRV_WRN("%s\n", "ctx_shift is not supported by this context, it will be disabled");
  1688. }
  1689. if (params_base.n_cache_reuse) {
  1690. params_base.n_cache_reuse = 0;
  1691. SRV_WRN("%s\n", "cache_reuse is not supported by this context, it will be disabled");
  1692. }
  1693. if (!params_base.speculative.model.path.empty()) {
  1694. SRV_ERR("%s\n", "err: speculative decode is not supported by this context");
  1695. return false;
  1696. }
  1697. }
  1698. return true;
  1699. }
  1700. void init() {
  1701. const int32_t n_ctx_slot = n_ctx / params_base.n_parallel;
  1702. SRV_INF("initializing slots, n_slots = %d\n", params_base.n_parallel);
  1703. for (int i = 0; i < params_base.n_parallel; i++) {
  1704. server_slot slot;
  1705. slot.id = i;
  1706. slot.ctx = ctx;
  1707. slot.n_ctx = n_ctx_slot;
  1708. slot.n_predict = params_base.n_predict;
  1709. slot.mctx = mctx;
  1710. slot.cache_tokens.has_mtmd = mctx != nullptr;
  1711. if (model_dft) {
  1712. slot.batch_spec = llama_batch_init(params_base.speculative.n_max + 1, 0, 1);
  1713. slot.ctx_dft = llama_init_from_model(model_dft, cparams_dft);
  1714. if (slot.ctx_dft == nullptr) {
  1715. SRV_ERR("%s", "failed to create draft context\n");
  1716. return;
  1717. }
  1718. slot.spec = common_speculative_init(slot.ctx_dft);
  1719. if (slot.spec == nullptr) {
  1720. SRV_ERR("%s", "failed to create speculator\n");
  1721. return;
  1722. }
  1723. }
  1724. SLT_INF(slot, "new slot n_ctx_slot = %d\n", slot.n_ctx);
  1725. slot.params.sampling = params_base.sampling;
  1726. slot.callback_on_release = [this](int) {
  1727. queue_tasks.pop_deferred_task();
  1728. };
  1729. slot.reset();
  1730. slots.push_back(std::move(slot));
  1731. }
  1732. default_generation_settings_for_props = slots[0].to_json();
  1733. // the update_slots() logic will always submit a maximum of n_batch or n_parallel tokens
  1734. // note that n_batch can be > n_ctx (e.g. for non-causal attention models such as BERT where the KV cache is not used)
  1735. {
  1736. const int32_t n_batch = llama_n_batch(ctx);
  1737. batch = llama_batch_init(std::max(n_batch, params_base.n_parallel), 0, 1);
  1738. }
  1739. metrics.init();
  1740. }
  1741. server_slot * get_slot_by_id(int id) {
  1742. for (server_slot & slot : slots) {
  1743. if (slot.id == id) {
  1744. return &slot;
  1745. }
  1746. }
  1747. return nullptr;
  1748. }
  1749. server_slot * get_available_slot(const server_task & task) {
  1750. server_slot * ret = nullptr;
  1751. // find the slot that has at least n% prompt similarity
  1752. if (ret == nullptr && slot_prompt_similarity != 0.0f) {
  1753. int lcs_len = 0;
  1754. float similarity = 0;
  1755. for (server_slot & slot : slots) {
  1756. // skip the slot if it is not available
  1757. if (slot.is_processing()) {
  1758. continue;
  1759. }
  1760. // skip the slot if it does not contains cached tokens
  1761. if (slot.cache_tokens.empty()) {
  1762. continue;
  1763. }
  1764. // length of the Longest Common Subsequence between the current slot's prompt and the input prompt
  1765. int cur_lcs_len = slot.cache_tokens.get_common_prefix(task.prompt_tokens);
  1766. // fraction of the common subsequence length compared to the current slot's prompt length
  1767. float cur_similarity = static_cast<float>(cur_lcs_len) / static_cast<int>(slot.cache_tokens.size());
  1768. // select the current slot if the criteria match
  1769. if (cur_lcs_len > lcs_len && cur_similarity > slot_prompt_similarity) {
  1770. lcs_len = cur_lcs_len;
  1771. similarity = cur_similarity;
  1772. ret = &slot;
  1773. }
  1774. }
  1775. if (ret != nullptr) {
  1776. SLT_DBG(*ret, "selected slot by lcs similarity, lcs_len = %d, similarity = %f\n", lcs_len, similarity);
  1777. }
  1778. }
  1779. // find the slot that has been least recently used
  1780. if (ret == nullptr) {
  1781. int64_t t_last = ggml_time_us();
  1782. for (server_slot & slot : slots) {
  1783. // skip the slot if it is not available
  1784. if (slot.is_processing()) {
  1785. continue;
  1786. }
  1787. // select the current slot if the criteria match
  1788. if (slot.t_last_used < t_last) {
  1789. t_last = slot.t_last_used;
  1790. ret = &slot;
  1791. }
  1792. }
  1793. if (ret != nullptr) {
  1794. SLT_DBG(*ret, "selected slot by lru, t_last = %" PRId64 "\n", t_last);
  1795. }
  1796. }
  1797. return ret;
  1798. }
  1799. bool launch_slot_with_task(server_slot & slot, server_task && task) {
  1800. slot.reset();
  1801. slot.id_task = task.id;
  1802. slot.index = task.index;
  1803. slot.task_type = task.type;
  1804. slot.params = std::move(task.params);
  1805. slot.prompt_tokens = std::move(task.prompt_tokens);
  1806. if (!are_lora_equal(slot.params.lora, slot.lora)) {
  1807. // if lora is changed, we cannot reuse cached tokens
  1808. slot.cache_tokens.clear();
  1809. slot.lora = slot.params.lora;
  1810. }
  1811. if (!slot.prompt_tokens.validate(ctx)) {
  1812. send_error(task, "Prompt contains invalid tokens", ERROR_TYPE_INVALID_REQUEST);
  1813. return false;
  1814. }
  1815. SLT_DBG(slot, "launching slot : %s\n", safe_json_to_str(slot.to_json()).c_str());
  1816. if (slot.n_predict > 0 && slot.params.n_predict > slot.n_predict) {
  1817. // Might be better to reject the request with a 400 ?
  1818. SLT_WRN(slot, "n_predict = %d exceeds server configuration, setting to %d\n", slot.params.n_predict, slot.n_predict);
  1819. slot.params.n_predict = slot.n_predict;
  1820. }
  1821. if (slot.params.ignore_eos && has_eos_token) {
  1822. slot.params.sampling.logit_bias.push_back({llama_vocab_eos(vocab), -INFINITY});
  1823. }
  1824. {
  1825. if (slot.smpl != nullptr) {
  1826. common_sampler_free(slot.smpl);
  1827. }
  1828. slot.smpl = common_sampler_init(model, slot.params.sampling);
  1829. if (slot.smpl == nullptr) {
  1830. // for now, the only error that may happen here is invalid grammar
  1831. send_error(task, "Failed to parse grammar", ERROR_TYPE_INVALID_REQUEST);
  1832. return false;
  1833. }
  1834. }
  1835. if (slot.ctx_dft) {
  1836. llama_batch_free(slot.batch_spec);
  1837. slot.batch_spec = llama_batch_init(slot.params.speculative.n_max + 1, 0, 1);
  1838. }
  1839. slot.state = SLOT_STATE_STARTED;
  1840. SLT_INF(slot, "%s", "processing task\n");
  1841. return true;
  1842. }
  1843. void kv_cache_clear() {
  1844. SRV_DBG("%s", "clearing KV cache\n");
  1845. // clear the entire KV cache
  1846. llama_kv_self_clear(ctx);
  1847. clean_kv_cache = false;
  1848. }
  1849. bool process_token(completion_token_output & result, server_slot & slot) {
  1850. // remember which tokens were sampled - used for repetition penalties during sampling
  1851. const std::string token_str = result.text_to_send;
  1852. slot.sampled = result.tok;
  1853. slot.generated_text += token_str;
  1854. if (slot.params.return_tokens) {
  1855. slot.generated_tokens.push_back(result.tok);
  1856. }
  1857. slot.has_next_token = true;
  1858. // check if there is incomplete UTF-8 character at the end
  1859. bool incomplete = validate_utf8(slot.generated_text) < slot.generated_text.size();
  1860. // search stop word and delete it
  1861. if (!incomplete) {
  1862. size_t pos = std::min(slot.n_sent_text, slot.generated_text.size());
  1863. const std::string str_test = slot.generated_text.substr(pos);
  1864. bool send_text = true;
  1865. size_t stop_pos = slot.find_stopping_strings(str_test, token_str.size(), true);
  1866. if (stop_pos != std::string::npos) {
  1867. slot.generated_text.erase(
  1868. slot.generated_text.begin() + pos + stop_pos,
  1869. slot.generated_text.end());
  1870. pos = std::min(slot.n_sent_text, slot.generated_text.size());
  1871. } else if (slot.has_next_token) {
  1872. stop_pos = slot.find_stopping_strings(str_test, token_str.size(), false);
  1873. send_text = stop_pos == std::string::npos;
  1874. }
  1875. // check if there is any token to predict
  1876. if (send_text) {
  1877. // no send the stop word in the response
  1878. result.text_to_send = slot.generated_text.substr(pos, std::string::npos);
  1879. slot.n_sent_text += result.text_to_send.size();
  1880. // add the token to slot queue and cache
  1881. } else {
  1882. result.text_to_send = "";
  1883. }
  1884. slot.add_token(result);
  1885. if (slot.params.stream) {
  1886. send_partial_response(slot, result);
  1887. }
  1888. }
  1889. if (incomplete) {
  1890. slot.has_next_token = true;
  1891. }
  1892. // if context shifting is disabled, make sure that we don't run out of context
  1893. if (!params_base.ctx_shift && slot.n_past + 1 >= slot.n_ctx) {
  1894. slot.stop = STOP_TYPE_LIMIT;
  1895. slot.has_next_token = false;
  1896. SLT_DBG(slot, "stopped due to running out of context, n_past = %d, n_ctx = %d\n", slot.n_past, slot.n_ctx);
  1897. }
  1898. // check the limits
  1899. if (slot.n_decoded > 0 && slot.has_next_token && !slot.has_budget(params_base)) {
  1900. slot.stop = STOP_TYPE_LIMIT;
  1901. slot.has_next_token = false;
  1902. SLT_DBG(slot, "stopped by limit, n_decoded = %d, n_predict = %d\n", slot.n_decoded, slot.params.n_predict);
  1903. }
  1904. if (slot.has_new_line) {
  1905. // require that each new line has a whitespace prefix (i.e. indentation) of at least slot.params.n_indent
  1906. if (slot.params.n_indent > 0) {
  1907. // check the current indentation
  1908. // TODO: improve by not doing it more than once for each new line
  1909. if (slot.last_nl_pos > 0) {
  1910. size_t pos = slot.last_nl_pos;
  1911. int n_indent = 0;
  1912. while (pos < slot.generated_text.size() && (slot.generated_text[pos] == ' ' || slot.generated_text[pos] == '\t')) {
  1913. n_indent++;
  1914. pos++;
  1915. }
  1916. if (pos < slot.generated_text.size() && n_indent < slot.params.n_indent) {
  1917. slot.stop = STOP_TYPE_LIMIT;
  1918. slot.has_next_token = false;
  1919. // cut the last line
  1920. slot.generated_text.erase(pos, std::string::npos);
  1921. SLT_DBG(slot, "stopped by indentation limit, n_decoded = %d, n_indent = %d\n", slot.n_decoded, n_indent);
  1922. }
  1923. }
  1924. // find the next new line
  1925. {
  1926. const size_t pos = slot.generated_text.find('\n', slot.last_nl_pos);
  1927. if (pos != std::string::npos) {
  1928. slot.last_nl_pos = pos + 1;
  1929. }
  1930. }
  1931. }
  1932. }
  1933. // check if there is a new line in the generated text
  1934. if (result.text_to_send.find('\n') != std::string::npos) {
  1935. slot.has_new_line = true;
  1936. // if we have seen a new line, we stop after a certain time limit, but only upon another new line
  1937. if (slot.params.t_max_predict_ms > 0 && (ggml_time_us() - slot.t_start_generation > 1000.0f*slot.params.t_max_predict_ms)) {
  1938. slot.stop = STOP_TYPE_LIMIT;
  1939. slot.has_next_token = false;
  1940. SLT_DBG(slot, "stopped by time limit, n_decoded = %d, t_max_predict_ms = %d ms\n", slot.n_decoded, (int) slot.params.t_max_predict_ms);
  1941. }
  1942. }
  1943. // if context shift is disabled, we stop when it reaches the context limit
  1944. if (slot.n_past >= slot.n_ctx) {
  1945. slot.truncated = true;
  1946. slot.stop = STOP_TYPE_LIMIT;
  1947. slot.has_next_token = false;
  1948. SLT_DBG(slot, "stopped due to running out of context capacity, n_past = %d, n_prompt_tokens = %d, n_decoded = %d, n_ctx = %d\n",
  1949. slot.n_decoded, slot.n_prompt_tokens, slot.n_past, slot.n_ctx);
  1950. }
  1951. if (llama_vocab_is_eog(vocab, result.tok)) {
  1952. slot.stop = STOP_TYPE_EOS;
  1953. slot.has_next_token = false;
  1954. SLT_DBG(slot, "%s", "stopped by EOS\n");
  1955. }
  1956. const auto n_ctx_train = llama_model_n_ctx_train(model);
  1957. if (slot.params.n_predict < 1 && slot.n_predict < 1 && slot.n_prompt_tokens + slot.n_decoded >= n_ctx_train) {
  1958. slot.truncated = true;
  1959. slot.stop = STOP_TYPE_LIMIT;
  1960. slot.has_next_token = false; // stop prediction
  1961. SLT_WRN(slot,
  1962. "n_predict (%d) is set for infinite generation. "
  1963. "Limiting generated tokens to n_ctx_train (%d) to avoid EOS-less generation infinite loop\n",
  1964. slot.params.n_predict, n_ctx_train);
  1965. }
  1966. SLT_DBG(slot, "n_decoded = %d, n_remaining = %d, next token: %5d '%s'\n", slot.n_decoded, slot.n_remaining, result.tok, token_str.c_str());
  1967. return slot.has_next_token; // continue
  1968. }
  1969. void populate_token_probs(const server_slot & slot, completion_token_output & result, bool post_sampling, bool special, int idx) {
  1970. size_t n_probs = slot.params.sampling.n_probs;
  1971. size_t n_vocab = llama_vocab_n_tokens(vocab);
  1972. if (post_sampling) {
  1973. const auto * cur_p = common_sampler_get_candidates(slot.smpl);
  1974. const size_t max_probs = cur_p->size;
  1975. // set probability for sampled token
  1976. for (size_t i = 0; i < max_probs; i++) {
  1977. if (cur_p->data[i].id == result.tok) {
  1978. result.prob = cur_p->data[i].p;
  1979. break;
  1980. }
  1981. }
  1982. // set probability for top n_probs tokens
  1983. result.probs.reserve(max_probs);
  1984. for (size_t i = 0; i < std::min(max_probs, n_probs); i++) {
  1985. result.probs.push_back({
  1986. cur_p->data[i].id,
  1987. common_token_to_piece(ctx, cur_p->data[i].id, special),
  1988. cur_p->data[i].p
  1989. });
  1990. }
  1991. } else {
  1992. // TODO: optimize this with min-p optimization
  1993. std::vector<llama_token_data> cur = get_token_probabilities(ctx, idx);
  1994. // set probability for sampled token
  1995. for (size_t i = 0; i < n_vocab; i++) {
  1996. // set probability for sampled token
  1997. if (cur[i].id == result.tok) {
  1998. result.prob = cur[i].p;
  1999. break;
  2000. }
  2001. }
  2002. // set probability for top n_probs tokens
  2003. result.probs.reserve(n_probs);
  2004. for (size_t i = 0; i < std::min(n_vocab, n_probs); i++) {
  2005. result.probs.push_back({
  2006. cur[i].id,
  2007. common_token_to_piece(ctx, cur[i].id, special),
  2008. cur[i].p
  2009. });
  2010. }
  2011. }
  2012. }
  2013. void send_error(const server_task & task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  2014. send_error(task.id, error, type);
  2015. }
  2016. void send_error(const server_slot & slot, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  2017. send_error(slot.id_task, error, type);
  2018. }
  2019. void send_error(const int id_task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  2020. SRV_ERR("task id = %d, error: %s\n", id_task, error.c_str());
  2021. auto res = std::make_unique<server_task_result_error>();
  2022. res->id = id_task;
  2023. res->err_type = type;
  2024. res->err_msg = error;
  2025. queue_results.send(std::move(res));
  2026. }
  2027. // if multimodal is enabled, send an error and return false
  2028. bool ensure_no_mtmd(const int id_task) {
  2029. if (mctx) {
  2030. send_error(id_task, "This feature is not supported by multimodal", ERROR_TYPE_NOT_SUPPORTED);
  2031. return false;
  2032. }
  2033. return true;
  2034. }
  2035. void send_partial_response(server_slot & slot, const completion_token_output & tkn) {
  2036. auto res = std::make_unique<server_task_result_cmpl_partial>();
  2037. res->id = slot.id_task;
  2038. res->index = slot.index;
  2039. res->content = tkn.text_to_send;
  2040. res->tokens = { tkn.tok };
  2041. res->n_decoded = slot.n_decoded;
  2042. res->n_prompt_tokens = slot.n_prompt_tokens;
  2043. res->post_sampling_probs = slot.params.post_sampling_probs;
  2044. res->verbose = slot.params.verbose;
  2045. res->oaicompat = slot.params.oaicompat;
  2046. res->oaicompat_model = slot.params.oaicompat_model;
  2047. res->oaicompat_cmpl_id = slot.params.oaicompat_cmpl_id;
  2048. // populate res.probs_output
  2049. if (slot.params.sampling.n_probs > 0) {
  2050. res->prob_output = tkn; // copy the token probs
  2051. }
  2052. // populate timings if this is final response or timings_per_token is enabled
  2053. if (slot.stop != STOP_TYPE_NONE || slot.params.timings_per_token) {
  2054. res->timings = slot.get_timings();
  2055. }
  2056. queue_results.send(std::move(res));
  2057. }
  2058. void send_final_response(server_slot & slot) {
  2059. auto res = std::make_unique<server_task_result_cmpl_final>();
  2060. res->id = slot.id_task;
  2061. res->id_slot = slot.id;
  2062. res->index = slot.index;
  2063. res->content = std::move(slot.generated_text);
  2064. res->tokens = std::move(slot.generated_tokens);
  2065. res->timings = slot.get_timings();
  2066. res->prompt = slot.prompt_tokens.detokenize(ctx, true);
  2067. res->response_fields = std::move(slot.params.response_fields);
  2068. res->truncated = slot.truncated;
  2069. res->n_decoded = slot.n_decoded;
  2070. res->n_prompt_tokens = slot.n_prompt_tokens;
  2071. res->n_tokens_cached = slot.n_past;
  2072. res->has_new_line = slot.has_new_line;
  2073. res->stopping_word = slot.stopping_word;
  2074. res->stop = slot.stop;
  2075. res->post_sampling_probs = slot.params.post_sampling_probs;
  2076. res->verbose = slot.params.verbose;
  2077. res->stream = slot.params.stream;
  2078. res->oaicompat = slot.params.oaicompat;
  2079. res->oaicompat_model = slot.params.oaicompat_model;
  2080. res->oaicompat_cmpl_id = slot.params.oaicompat_cmpl_id;
  2081. res->oaicompat_chat_format = slot.params.oaicompat_chat_format;
  2082. // populate res.probs_output
  2083. if (slot.params.sampling.n_probs > 0) {
  2084. if (!slot.params.stream && slot.stop == STOP_TYPE_WORD) {
  2085. const llama_tokens stop_word_toks = common_tokenize(ctx, slot.stopping_word, false);
  2086. size_t safe_offset = std::min(slot.generated_token_probs.size(), stop_word_toks.size());
  2087. res->probs_output = std::vector<completion_token_output>(
  2088. slot.generated_token_probs.begin(),
  2089. slot.generated_token_probs.end() - safe_offset);
  2090. } else {
  2091. res->probs_output = std::vector<completion_token_output>(
  2092. slot.generated_token_probs.begin(),
  2093. slot.generated_token_probs.end());
  2094. }
  2095. }
  2096. res->generation_params = slot.params; // copy the parameters
  2097. queue_results.send(std::move(res));
  2098. }
  2099. void send_embedding(const server_slot & slot, const llama_batch & batch) {
  2100. auto res = std::make_unique<server_task_result_embd>();
  2101. res->id = slot.id_task;
  2102. res->index = slot.index;
  2103. res->n_tokens = slot.n_prompt_tokens;
  2104. res->oaicompat = slot.params.oaicompat;
  2105. const int n_embd = llama_model_n_embd(model);
  2106. std::vector<float> embd_res(n_embd, 0.0f);
  2107. for (int i = 0; i < batch.n_tokens; ++i) {
  2108. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  2109. continue;
  2110. }
  2111. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  2112. if (embd == NULL) {
  2113. embd = llama_get_embeddings_ith(ctx, i);
  2114. }
  2115. if (embd == NULL) {
  2116. SLT_ERR(slot, "failed to get embeddings, token = %d, seq_id = %d\n", batch.token[i], batch.seq_id[i][0]);
  2117. res->embedding.push_back(std::vector<float>(n_embd, 0.0f));
  2118. continue;
  2119. }
  2120. // normalize only when there is pooling
  2121. // TODO: configurable
  2122. if (llama_pooling_type(slot.ctx) != LLAMA_POOLING_TYPE_NONE) {
  2123. common_embd_normalize(embd, embd_res.data(), n_embd, 2);
  2124. res->embedding.push_back(embd_res);
  2125. } else {
  2126. res->embedding.push_back({ embd, embd + n_embd });
  2127. }
  2128. }
  2129. SLT_DBG(slot, "%s", "sending embeddings\n");
  2130. queue_results.send(std::move(res));
  2131. }
  2132. void send_rerank(const server_slot & slot, const llama_batch & batch) {
  2133. auto res = std::make_unique<server_task_result_rerank>();
  2134. res->id = slot.id_task;
  2135. res->index = slot.index;
  2136. res->n_tokens = slot.n_prompt_tokens;
  2137. for (int i = 0; i < batch.n_tokens; ++i) {
  2138. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  2139. continue;
  2140. }
  2141. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  2142. if (embd == NULL) {
  2143. embd = llama_get_embeddings_ith(ctx, i);
  2144. }
  2145. if (embd == NULL) {
  2146. SLT_ERR(slot, "failed to get embeddings, token = %d, seq_id = %d\n", batch.token[i], batch.seq_id[i][0]);
  2147. res->score = -1e6;
  2148. continue;
  2149. }
  2150. res->score = embd[0];
  2151. }
  2152. SLT_DBG(slot, "sending rerank result, res.score = %f\n", res->score);
  2153. queue_results.send(std::move(res));
  2154. }
  2155. //
  2156. // Functions to create new task(s) and receive result(s)
  2157. //
  2158. void cancel_tasks(const std::unordered_set<int> & id_tasks) {
  2159. std::vector<server_task> cancel_tasks;
  2160. cancel_tasks.reserve(id_tasks.size());
  2161. for (const auto & id_task : id_tasks) {
  2162. SRV_WRN("cancel task, id_task = %d\n", id_task);
  2163. server_task task(SERVER_TASK_TYPE_CANCEL);
  2164. task.id_target = id_task;
  2165. queue_results.remove_waiting_task_id(id_task);
  2166. cancel_tasks.push_back(std::move(task));
  2167. }
  2168. // push to beginning of the queue, so it has highest priority
  2169. queue_tasks.post(std::move(cancel_tasks), true);
  2170. }
  2171. // receive the results from task(s)
  2172. void receive_multi_results(
  2173. const std::unordered_set<int> & id_tasks,
  2174. const std::function<void(std::vector<server_task_result_ptr>&)> & result_handler,
  2175. const std::function<void(json)> & error_handler,
  2176. const std::function<bool()> & is_connection_closed) {
  2177. std::vector<server_task_result_ptr> results(id_tasks.size());
  2178. for (int i = 0; i < (int)id_tasks.size(); i++) {
  2179. server_task_result_ptr result = queue_results.recv_with_timeout(id_tasks, HTTP_POLLING_SECONDS);
  2180. if (is_connection_closed()) {
  2181. cancel_tasks(id_tasks);
  2182. return;
  2183. }
  2184. if (result == nullptr) {
  2185. i--; // retry
  2186. continue;
  2187. }
  2188. if (result->is_error()) {
  2189. error_handler(result->to_json());
  2190. cancel_tasks(id_tasks);
  2191. return;
  2192. }
  2193. GGML_ASSERT(
  2194. dynamic_cast<server_task_result_cmpl_final*>(result.get()) != nullptr
  2195. || dynamic_cast<server_task_result_embd*>(result.get()) != nullptr
  2196. || dynamic_cast<server_task_result_rerank*>(result.get()) != nullptr
  2197. );
  2198. const size_t idx = result->get_index();
  2199. GGML_ASSERT(idx < results.size() && "index out of range");
  2200. results[idx] = std::move(result);
  2201. }
  2202. result_handler(results);
  2203. }
  2204. // receive the results from task(s), in stream mode
  2205. void receive_cmpl_results_stream(
  2206. const std::unordered_set<int> & id_tasks,
  2207. const std::function<bool(server_task_result_ptr&)> & result_handler,
  2208. const std::function<void(json)> & error_handler,
  2209. const std::function<bool()> & is_connection_closed) {
  2210. size_t n_finished = 0;
  2211. while (true) {
  2212. server_task_result_ptr result = queue_results.recv_with_timeout(id_tasks, HTTP_POLLING_SECONDS);
  2213. if (is_connection_closed()) {
  2214. cancel_tasks(id_tasks);
  2215. return;
  2216. }
  2217. if (result == nullptr) {
  2218. continue; // retry
  2219. }
  2220. if (result->is_error()) {
  2221. error_handler(result->to_json());
  2222. cancel_tasks(id_tasks);
  2223. return;
  2224. }
  2225. GGML_ASSERT(
  2226. dynamic_cast<server_task_result_cmpl_partial*>(result.get()) != nullptr
  2227. || dynamic_cast<server_task_result_cmpl_final*>(result.get()) != nullptr
  2228. );
  2229. if (!result_handler(result)) {
  2230. cancel_tasks(id_tasks);
  2231. break;
  2232. }
  2233. if (result->is_stop()) {
  2234. if (++n_finished == id_tasks.size()) {
  2235. break;
  2236. }
  2237. }
  2238. }
  2239. }
  2240. //
  2241. // Functions to process the task
  2242. //
  2243. void process_single_task(server_task && task) {
  2244. switch (task.type) {
  2245. case SERVER_TASK_TYPE_COMPLETION:
  2246. case SERVER_TASK_TYPE_INFILL:
  2247. case SERVER_TASK_TYPE_EMBEDDING:
  2248. case SERVER_TASK_TYPE_RERANK:
  2249. {
  2250. const int id_slot = task.id_selected_slot;
  2251. server_slot * slot = id_slot != -1 ? get_slot_by_id(id_slot) : get_available_slot(task);
  2252. if (slot == nullptr) {
  2253. // if no slot is available, we defer this task for processing later
  2254. SRV_DBG("no slot is available, defer task, id_task = %d\n", task.id);
  2255. queue_tasks.defer(std::move(task));
  2256. break;
  2257. }
  2258. if (slot->is_processing()) {
  2259. // if requested slot is unavailable, we defer this task for processing later
  2260. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  2261. queue_tasks.defer(std::move(task));
  2262. break;
  2263. }
  2264. if (!launch_slot_with_task(*slot, std::move(task))) {
  2265. SRV_ERR("failed to launch slot with task, id_task = %d\n", task.id);
  2266. break;
  2267. }
  2268. } break;
  2269. case SERVER_TASK_TYPE_CANCEL:
  2270. {
  2271. // release slot linked with the task id
  2272. for (auto & slot : slots) {
  2273. if (slot.id_task == task.id_target) {
  2274. slot.release();
  2275. break;
  2276. }
  2277. }
  2278. } break;
  2279. case SERVER_TASK_TYPE_NEXT_RESPONSE:
  2280. {
  2281. // do nothing
  2282. } break;
  2283. case SERVER_TASK_TYPE_METRICS:
  2284. {
  2285. json slots_data = json::array();
  2286. int n_idle_slots = 0;
  2287. int n_processing_slots = 0;
  2288. for (server_slot & slot : slots) {
  2289. json slot_data = slot.to_json();
  2290. if (slot.is_processing()) {
  2291. n_processing_slots++;
  2292. } else {
  2293. n_idle_slots++;
  2294. }
  2295. slots_data.push_back(slot_data);
  2296. }
  2297. SRV_DBG("n_idle_slots = %d, n_processing_slots = %d\n", n_idle_slots, n_processing_slots);
  2298. auto res = std::make_unique<server_task_result_metrics>();
  2299. res->id = task.id;
  2300. res->slots_data = std::move(slots_data);
  2301. res->n_idle_slots = n_idle_slots;
  2302. res->n_processing_slots = n_processing_slots;
  2303. res->n_tasks_deferred = queue_tasks.queue_tasks_deferred.size();
  2304. res->t_start = metrics.t_start;
  2305. res->n_prompt_tokens_processed_total = metrics.n_prompt_tokens_processed_total;
  2306. res->t_prompt_processing_total = metrics.t_prompt_processing_total;
  2307. res->n_tokens_predicted_total = metrics.n_tokens_predicted_total;
  2308. res->t_tokens_generation_total = metrics.t_tokens_generation_total;
  2309. res->n_prompt_tokens_processed = metrics.n_prompt_tokens_processed;
  2310. res->t_prompt_processing = metrics.t_prompt_processing;
  2311. res->n_tokens_predicted = metrics.n_tokens_predicted;
  2312. res->t_tokens_generation = metrics.t_tokens_generation;
  2313. res->n_decode_total = metrics.n_decode_total;
  2314. res->n_busy_slots_total = metrics.n_busy_slots_total;
  2315. if (task.metrics_reset_bucket) {
  2316. metrics.reset_bucket();
  2317. }
  2318. queue_results.send(std::move(res));
  2319. } break;
  2320. case SERVER_TASK_TYPE_SLOT_SAVE:
  2321. {
  2322. if (!ensure_no_mtmd(task.id)) {
  2323. break;
  2324. }
  2325. int id_slot = task.slot_action.slot_id;
  2326. server_slot * slot = get_slot_by_id(id_slot);
  2327. if (slot == nullptr) {
  2328. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  2329. break;
  2330. }
  2331. if (slot->is_processing()) {
  2332. // if requested slot is unavailable, we defer this task for processing later
  2333. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  2334. queue_tasks.defer(std::move(task));
  2335. break;
  2336. }
  2337. const size_t token_count = slot->cache_tokens.size();
  2338. const int64_t t_start = ggml_time_us();
  2339. std::string filename = task.slot_action.filename;
  2340. std::string filepath = task.slot_action.filepath;
  2341. const llama_tokens & tokens = slot->cache_tokens.get_text_tokens();
  2342. const size_t nwrite = llama_state_seq_save_file(ctx, filepath.c_str(), slot->id, tokens.data(), token_count);
  2343. const int64_t t_end = ggml_time_us();
  2344. const double t_save_ms = (t_end - t_start) / 1000.0;
  2345. auto res = std::make_unique<server_task_result_slot_save_load>();
  2346. res->id = task.id;
  2347. res->id_slot = id_slot;
  2348. res->filename = filename;
  2349. res->is_save = true;
  2350. res->n_tokens = token_count;
  2351. res->n_bytes = nwrite;
  2352. res->t_ms = t_save_ms;
  2353. queue_results.send(std::move(res));
  2354. } break;
  2355. case SERVER_TASK_TYPE_SLOT_RESTORE:
  2356. {
  2357. if (!ensure_no_mtmd(task.id)) break;
  2358. int id_slot = task.slot_action.slot_id;
  2359. server_slot * slot = get_slot_by_id(id_slot);
  2360. if (slot == nullptr) {
  2361. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  2362. break;
  2363. }
  2364. if (slot->is_processing()) {
  2365. // if requested slot is unavailable, we defer this task for processing later
  2366. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  2367. queue_tasks.defer(std::move(task));
  2368. break;
  2369. }
  2370. const int64_t t_start = ggml_time_us();
  2371. std::string filename = task.slot_action.filename;
  2372. std::string filepath = task.slot_action.filepath;
  2373. llama_tokens tokens;
  2374. tokens.resize(slot->n_ctx);
  2375. size_t token_count = 0;
  2376. size_t nread = llama_state_seq_load_file(ctx, filepath.c_str(), slot->id, tokens.data(), tokens.size(), &token_count);
  2377. if (nread == 0) {
  2378. slot->cache_tokens.clear(); // KV may already been invalidated?
  2379. send_error(task, "Unable to restore slot, no available space in KV cache or invalid slot save file", ERROR_TYPE_INVALID_REQUEST);
  2380. break;
  2381. }
  2382. tokens.resize(token_count);
  2383. slot->cache_tokens.clear();
  2384. slot->cache_tokens.insert(tokens);
  2385. const int64_t t_end = ggml_time_us();
  2386. const double t_restore_ms = (t_end - t_start) / 1000.0;
  2387. auto res = std::make_unique<server_task_result_slot_save_load>();
  2388. res->id = task.id;
  2389. res->id_slot = id_slot;
  2390. res->filename = filename;
  2391. res->is_save = false;
  2392. res->n_tokens = token_count;
  2393. res->n_bytes = nread;
  2394. res->t_ms = t_restore_ms;
  2395. queue_results.send(std::move(res));
  2396. } break;
  2397. case SERVER_TASK_TYPE_SLOT_ERASE:
  2398. {
  2399. if (!ensure_no_mtmd(task.id)) break;
  2400. int id_slot = task.slot_action.slot_id;
  2401. server_slot * slot = get_slot_by_id(id_slot);
  2402. if (slot == nullptr) {
  2403. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  2404. break;
  2405. }
  2406. if (slot->is_processing()) {
  2407. // if requested slot is unavailable, we defer this task for processing later
  2408. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  2409. queue_tasks.defer(std::move(task));
  2410. break;
  2411. }
  2412. // Erase token cache
  2413. const size_t n_erased = slot->cache_tokens.size();
  2414. llama_kv_self_seq_rm(ctx, slot->id, -1, -1);
  2415. slot->cache_tokens.clear();
  2416. auto res = std::make_unique<server_task_result_slot_erase>();
  2417. res->id = task.id;
  2418. res->id_slot = id_slot;
  2419. res->n_erased = n_erased;
  2420. queue_results.send(std::move(res));
  2421. } break;
  2422. case SERVER_TASK_TYPE_SET_LORA:
  2423. {
  2424. params_base.lora_adapters = std::move(task.set_lora);
  2425. auto res = std::make_unique<server_task_result_apply_lora>();
  2426. res->id = task.id;
  2427. queue_results.send(std::move(res));
  2428. } break;
  2429. }
  2430. }
  2431. void update_slots() {
  2432. // check if all slots are idle
  2433. {
  2434. bool all_idle = true;
  2435. for (auto & slot : slots) {
  2436. if (slot.is_processing()) {
  2437. all_idle = false;
  2438. break;
  2439. }
  2440. }
  2441. if (all_idle) {
  2442. SRV_INF("%s", "all slots are idle\n");
  2443. if (clean_kv_cache) {
  2444. kv_cache_clear();
  2445. }
  2446. return;
  2447. }
  2448. }
  2449. {
  2450. SRV_DBG("%s", "posting NEXT_RESPONSE\n");
  2451. server_task task(SERVER_TASK_TYPE_NEXT_RESPONSE);
  2452. task.id = queue_tasks.get_new_id();
  2453. queue_tasks.post(std::move(task));
  2454. }
  2455. // apply context-shift if needed
  2456. // TODO: simplify and improve
  2457. for (server_slot & slot : slots) {
  2458. if (slot.is_processing() && slot.n_past + 1 >= slot.n_ctx) {
  2459. if (!params_base.ctx_shift) {
  2460. // this check is redundant (for good)
  2461. // we should never get here, because generation should already stopped in process_token()
  2462. slot.release();
  2463. send_error(slot, "context shift is disabled", ERROR_TYPE_SERVER);
  2464. continue;
  2465. }
  2466. if (mctx) {
  2467. // we should never reach this because params_base.ctx_shift is automatically disabled if mmproj is loaded
  2468. // we don't support ctx_shift because an image chunk may contains multiple tokens
  2469. GGML_ABORT("not supported by multimodal");
  2470. }
  2471. // Shift context
  2472. const int n_keep = slot.params.n_keep + add_bos_token;
  2473. const int n_left = slot.n_past - n_keep;
  2474. const int n_discard = slot.params.n_discard ? slot.params.n_discard : (n_left / 2);
  2475. SLT_WRN(slot, "slot context shift, n_keep = %d, n_left = %d, n_discard = %d\n", n_keep, n_left, n_discard);
  2476. llama_kv_self_seq_rm (ctx, slot.id, n_keep , n_keep + n_discard);
  2477. llama_kv_self_seq_add(ctx, slot.id, n_keep + n_discard, slot.n_past, -n_discard);
  2478. // add generated tokens to cache
  2479. {
  2480. llama_tokens new_tokens = slot.cache_tokens.get_text_tokens(); // copy
  2481. for (size_t i = n_keep + n_discard; i < new_tokens.size(); i++) {
  2482. new_tokens[i - n_discard] = new_tokens[i];
  2483. }
  2484. new_tokens.resize(slot.cache_tokens.size() - n_discard);
  2485. slot.cache_tokens.clear();
  2486. slot.cache_tokens.insert(new_tokens);
  2487. }
  2488. slot.n_past -= n_discard;
  2489. slot.truncated = true;
  2490. }
  2491. }
  2492. // start populating the batch for this iteration
  2493. common_batch_clear(batch);
  2494. // track if given slot can be batched with slots already in the batch
  2495. server_slot * slot_batched = nullptr;
  2496. auto accept_special_token = [&](server_slot & slot, llama_token token) {
  2497. return params_base.special || slot.params.sampling.preserved_tokens.find(token) != slot.params.sampling.preserved_tokens.end();
  2498. };
  2499. // frist, add sampled tokens from any ongoing sequences
  2500. for (auto & slot : slots) {
  2501. if (slot.state != SLOT_STATE_GENERATING) {
  2502. continue;
  2503. }
  2504. // check if we can batch this slot with the previous one
  2505. if (!slot_batched) {
  2506. slot_batched = &slot;
  2507. } else if (!slot_batched->can_batch_with(slot)) {
  2508. continue;
  2509. }
  2510. slot.i_batch = batch.n_tokens;
  2511. common_batch_add(batch, slot.sampled, slot.n_past, { slot.id }, true);
  2512. slot.n_past += 1;
  2513. slot.cache_tokens.push_back(slot.sampled);
  2514. SLT_DBG(slot, "slot decode token, n_ctx = %d, n_past = %d, n_cache_tokens = %d, truncated = %d\n",
  2515. slot.n_ctx, slot.n_past, (int) slot.cache_tokens.size(), slot.truncated);
  2516. }
  2517. // process in chunks of params.n_batch
  2518. int32_t n_batch = llama_n_batch(ctx);
  2519. int32_t n_ubatch = llama_n_ubatch(ctx);
  2520. // next, batch any pending prompts without exceeding n_batch
  2521. if (params_base.cont_batching || batch.n_tokens == 0) {
  2522. for (auto & slot : slots) {
  2523. // check if we can batch this slot with the previous one
  2524. if (slot.is_processing()) {
  2525. if (!slot_batched) {
  2526. slot_batched = &slot;
  2527. } else if (!slot_batched->can_batch_with(slot)) {
  2528. continue;
  2529. }
  2530. }
  2531. // this slot still has a prompt to be processed
  2532. if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_STARTED) {
  2533. auto & prompt_tokens = slot.prompt_tokens;
  2534. // TODO: maybe move branch to outside of this loop in the future
  2535. if (slot.state == SLOT_STATE_STARTED) {
  2536. slot.t_start_process_prompt = ggml_time_us();
  2537. slot.t_start_generation = 0;
  2538. slot.n_past = 0;
  2539. slot.n_prompt_tokens = prompt_tokens.size();
  2540. slot.state = SLOT_STATE_PROCESSING_PROMPT;
  2541. SLT_INF(slot, "new prompt, n_ctx_slot = %d, n_keep = %d, n_prompt_tokens = %d\n", slot.n_ctx, slot.params.n_keep, slot.n_prompt_tokens);
  2542. // print prompt tokens (for debugging)
  2543. /*if (1) {
  2544. // first 16 tokens (avoid flooding logs)
  2545. for (int i = 0; i < std::min<int>(16, prompt_tokens.size()); i++) {
  2546. SLT_DBG(slot, "prompt token %3d: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  2547. }
  2548. } else {
  2549. // all
  2550. for (int i = 0; i < (int) prompt_tokens.size(); i++) {
  2551. SLT_DBG(slot, "prompt token %3d: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  2552. }
  2553. }*/
  2554. // empty prompt passed -> release the slot and send empty response
  2555. if (prompt_tokens.empty()) {
  2556. SLT_WRN(slot, "%s", "empty prompt - releasing slot\n");
  2557. slot.release();
  2558. slot.print_timings();
  2559. send_final_response(slot);
  2560. continue;
  2561. }
  2562. if (slot.is_non_causal()) {
  2563. if (slot.n_prompt_tokens > n_ubatch) {
  2564. slot.release();
  2565. send_error(slot, "input is too large to process. increase the physical batch size", ERROR_TYPE_SERVER);
  2566. continue;
  2567. }
  2568. if (slot.n_prompt_tokens > slot.n_ctx) {
  2569. slot.release();
  2570. send_error(slot, "input is larger than the max context size. skipping", ERROR_TYPE_SERVER);
  2571. continue;
  2572. }
  2573. } else {
  2574. if (!params_base.ctx_shift) {
  2575. // if context shift is disabled, we make sure prompt size is smaller than KV size
  2576. // TODO: there should be a separate parameter that control prompt truncation
  2577. // context shift should be applied only during the generation phase
  2578. if (slot.n_prompt_tokens >= slot.n_ctx) {
  2579. slot.release();
  2580. send_error(slot, "the request exceeds the available context size. try increasing the context size or enable context shift", ERROR_TYPE_INVALID_REQUEST);
  2581. continue;
  2582. }
  2583. }
  2584. if (slot.params.n_keep < 0) {
  2585. slot.params.n_keep = slot.n_prompt_tokens;
  2586. }
  2587. slot.params.n_keep = std::min(slot.n_ctx - 4, slot.params.n_keep);
  2588. // if input prompt is too big, truncate it
  2589. if (slot.n_prompt_tokens >= slot.n_ctx) {
  2590. if (mctx) {
  2591. // we should never reach this
  2592. GGML_ABORT("not supported by multimodal");
  2593. }
  2594. const int n_left = slot.n_ctx - slot.params.n_keep;
  2595. const int n_block_size = n_left / 2;
  2596. const int erased_blocks = (slot.n_prompt_tokens - slot.params.n_keep - n_block_size) / n_block_size;
  2597. const llama_tokens & curr_tokens = slot.prompt_tokens.get_text_tokens();
  2598. llama_tokens new_tokens(
  2599. curr_tokens.begin(),
  2600. curr_tokens.begin() + slot.params.n_keep);
  2601. new_tokens.insert(
  2602. new_tokens.end(),
  2603. curr_tokens.begin() + slot.params.n_keep + erased_blocks * n_block_size,
  2604. curr_tokens.end());
  2605. prompt_tokens.clear();
  2606. prompt_tokens.insert(new_tokens);
  2607. slot.truncated = true;
  2608. slot.n_prompt_tokens = prompt_tokens.size();
  2609. SLT_WRN(slot, "input truncated, n_ctx = %d, n_keep = %d, n_left = %d, n_prompt_tokens = %d\n", slot.n_ctx, slot.params.n_keep, n_left, slot.n_prompt_tokens);
  2610. GGML_ASSERT(slot.n_prompt_tokens < slot.n_ctx);
  2611. }
  2612. if (slot.params.cache_prompt) {
  2613. // reuse any previously computed tokens that are common with the new prompt
  2614. slot.n_past = slot.cache_tokens.get_common_prefix(prompt_tokens);
  2615. // reuse chunks from the cached prompt by shifting their KV cache in the new position
  2616. if (params_base.n_cache_reuse > 0) {
  2617. size_t head_c = slot.n_past; // cache
  2618. size_t head_p = slot.n_past; // current prompt
  2619. if (mctx) {
  2620. // we should never reach this
  2621. GGML_ABORT("not supported by multimodal");
  2622. }
  2623. SLT_DBG(slot, "trying to reuse chunks with size > %d, slot.n_past = %d\n", params_base.n_cache_reuse, slot.n_past);
  2624. while (head_c < slot.cache_tokens.size() &&
  2625. head_p < prompt_tokens.size()) {
  2626. size_t n_match = 0;
  2627. while (head_c + n_match < slot.cache_tokens.size() &&
  2628. head_p + n_match < prompt_tokens.size() &&
  2629. slot.cache_tokens[head_c + n_match] == prompt_tokens[head_p + n_match]) {
  2630. n_match++;
  2631. }
  2632. if (n_match >= (size_t) params_base.n_cache_reuse) {
  2633. SLT_INF(slot, "reusing chunk with size %zu, shifting KV cache [%zu, %zu) -> [%zu, %zu)\n", n_match, head_c, head_c + n_match, head_p, head_p + n_match);
  2634. //for (size_t i = head_p; i < head_p + n_match; i++) {
  2635. // SLT_DBG(slot, "cache token %3zu: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  2636. //}
  2637. const int64_t kv_shift = (int64_t) head_p - (int64_t) head_c;
  2638. llama_kv_self_seq_rm (ctx, slot.id, head_p, head_c);
  2639. llama_kv_self_seq_add(ctx, slot.id, head_c, head_c + n_match, kv_shift);
  2640. for (size_t i = 0; i < n_match; i++) {
  2641. slot.cache_tokens.set_token(head_p + i, slot.cache_tokens[head_c + i]);
  2642. slot.n_past++;
  2643. }
  2644. head_c += n_match;
  2645. head_p += n_match;
  2646. } else {
  2647. head_c += 1;
  2648. }
  2649. }
  2650. SLT_DBG(slot, "after context reuse, new slot.n_past = %d\n", slot.n_past);
  2651. }
  2652. } else {
  2653. // if we don't cache the prompt, we have to remove the entire KV cache
  2654. llama_kv_self_seq_rm(ctx, slot.id, 0, -1);
  2655. slot.n_past = 0;
  2656. slot.cache_tokens.clear(); // TODO: not needed, will be cleared later via "keep_first()"
  2657. }
  2658. if (slot.n_past > 0 && slot.n_past < (int) slot.cache_tokens.size()) {
  2659. if (llama_kv_self_seq_pos_min(ctx, slot.id) > 0) {
  2660. SLT_WRN(slot, "forcing full prompt re-processing due to lack of cache data (likely due to SWA, see %s)\n",
  2661. "https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055");
  2662. slot.n_past = 0;
  2663. }
  2664. }
  2665. }
  2666. if (slot.n_past == slot.n_prompt_tokens && slot.n_past > 0) {
  2667. // we have to evaluate at least 1 token to generate logits.
  2668. SLT_WRN(slot, "need to evaluate at least 1 token to generate logits, n_past = %d, n_prompt_tokens = %d\n", slot.n_past, slot.n_prompt_tokens);
  2669. slot.n_past--;
  2670. }
  2671. slot.n_prompt_tokens_processed = 0;
  2672. }
  2673. // non-causal tasks require to fit the entire prompt in the physical batch
  2674. if (slot.is_non_causal()) {
  2675. // cannot fit the prompt in the current batch - will try next iter
  2676. if (batch.n_tokens + slot.n_prompt_tokens > n_batch) {
  2677. continue;
  2678. }
  2679. }
  2680. // keep only the common part
  2681. if (!llama_kv_self_seq_rm(ctx, slot.id, slot.n_past, -1)) {
  2682. // could not partially delete (likely using a non-Transformer model)
  2683. llama_kv_self_seq_rm(ctx, slot.id, -1, -1);
  2684. // there is no common part left
  2685. slot.n_past = 0;
  2686. }
  2687. SLT_INF(slot, "kv cache rm [%d, end)\n", slot.n_past);
  2688. // remove the non-common part from the cache
  2689. slot.cache_tokens.keep_first(slot.n_past);
  2690. // check if we should process the image
  2691. if (slot.n_past < slot.n_prompt_tokens
  2692. && slot.prompt_tokens[slot.n_past] == LLAMA_TOKEN_NULL) {
  2693. // process the image
  2694. int32_t new_n_past;
  2695. int32_t res = slot.prompt_tokens.process_chunk(ctx, mctx, slot.n_past, slot.id, new_n_past);
  2696. int32_t n_pos = new_n_past - slot.n_past;
  2697. if (res != 0) {
  2698. SLT_ERR(slot, "failed to process image, res = %d\n", res);
  2699. slot.release();
  2700. send_error(slot, "failed to process image", ERROR_TYPE_SERVER);
  2701. continue;
  2702. }
  2703. // add the image chunk to cache
  2704. {
  2705. const auto & chunk = slot.prompt_tokens.find_chunk(slot.n_past);
  2706. slot.cache_tokens.push_back(chunk.get()); // copy
  2707. }
  2708. slot.n_past += n_pos;
  2709. slot.n_prompt_tokens_processed += n_pos;
  2710. }
  2711. // add prompt tokens for processing in the current batch
  2712. while (slot.n_past < slot.n_prompt_tokens && batch.n_tokens < n_batch) {
  2713. // get next token to process
  2714. llama_token cur_tok = slot.prompt_tokens[slot.n_past];
  2715. if (cur_tok == LLAMA_TOKEN_NULL) {
  2716. break; // end of text chunk
  2717. }
  2718. // without pooling, we want to output the embeddings for all the tokens in the batch
  2719. const bool need_embd = slot.task_type == SERVER_TASK_TYPE_EMBEDDING && llama_pooling_type(slot.ctx) == LLAMA_POOLING_TYPE_NONE;
  2720. common_batch_add(batch, cur_tok, slot.n_past, { slot.id }, need_embd);
  2721. slot.cache_tokens.push_back(cur_tok);
  2722. slot.n_prompt_tokens_processed++;
  2723. slot.n_past++;
  2724. }
  2725. // SLT_INF(slot, "new cache_tokens: %s\n", slot.cache_tokens.str().c_str());
  2726. SLT_INF(slot, "prompt processing progress, n_past = %d, n_tokens = %d, progress = %f\n", slot.n_past, batch.n_tokens, (float) slot.n_prompt_tokens_processed / slot.n_prompt_tokens);
  2727. // entire prompt has been processed
  2728. if (slot.n_past == slot.n_prompt_tokens) {
  2729. slot.state = SLOT_STATE_DONE_PROMPT;
  2730. GGML_ASSERT(batch.n_tokens > 0);
  2731. GGML_ASSERT((size_t) slot.n_prompt_tokens == slot.prompt_tokens.size());
  2732. common_sampler_reset(slot.smpl);
  2733. // Process all prompt tokens through sampler system
  2734. for (int i = 0; i < slot.n_prompt_tokens; ++i) {
  2735. llama_token id = slot.prompt_tokens[i];
  2736. if (id != LLAMA_TOKEN_NULL) {
  2737. common_sampler_accept(slot.smpl, id, false);
  2738. }
  2739. }
  2740. // extract the logits only for the last token
  2741. batch.logits[batch.n_tokens - 1] = true;
  2742. slot.n_decoded = 0;
  2743. slot.i_batch = batch.n_tokens - 1;
  2744. SLT_INF(slot, "prompt done, n_past = %d, n_tokens = %d\n", slot.n_past, batch.n_tokens);
  2745. }
  2746. }
  2747. if (batch.n_tokens >= n_batch) {
  2748. break;
  2749. }
  2750. }
  2751. }
  2752. if (batch.n_tokens == 0) {
  2753. SRV_WRN("%s", "no tokens to decode\n");
  2754. return;
  2755. }
  2756. SRV_DBG("decoding batch, n_tokens = %d\n", batch.n_tokens);
  2757. if (slot_batched) {
  2758. // make sure we're in the right embedding mode
  2759. llama_set_embeddings(ctx, slot_batched->is_non_causal());
  2760. // apply lora, only need to do it once per batch
  2761. common_set_adapter_lora(ctx, slot_batched->lora);
  2762. }
  2763. // process the created batch of tokens
  2764. for (int32_t i = 0; i < batch.n_tokens; i += n_batch) {
  2765. const int32_t n_tokens = std::min(n_batch, batch.n_tokens - i);
  2766. llama_batch batch_view = {
  2767. n_tokens,
  2768. batch.token + i,
  2769. nullptr,
  2770. batch.pos + i,
  2771. batch.n_seq_id + i,
  2772. batch.seq_id + i,
  2773. batch.logits + i,
  2774. };
  2775. int ret = 0;
  2776. if (params_base.embedding || params_base.reranking) {
  2777. ret = llama_encode(ctx, batch_view);
  2778. } else {
  2779. ret = llama_decode(ctx, batch_view);
  2780. }
  2781. metrics.on_decoded(slots);
  2782. if (ret != 0) {
  2783. if (n_batch == 1 || ret < 0) {
  2784. // if you get here, it means the KV cache is full - try increasing it via the context size
  2785. SRV_ERR("failed to decode the batch: KV cache is full - try increasing it via the context size, i = %d, n_batch = %d, ret = %d\n", i, n_batch, ret);
  2786. for (auto & slot : slots) {
  2787. slot.release();
  2788. send_error(slot, "Input prompt is too big compared to KV size. Please try increasing KV size.");
  2789. }
  2790. break; // break loop of n_batch
  2791. }
  2792. // retry with half the batch size to try to find a free slot in the KV cache
  2793. n_batch /= 2;
  2794. i -= n_batch;
  2795. SRV_WRN("failed to find free space in the KV cache, retrying with smaller batch size - try increasing it via the context size or enable defragmentation, i = %d, n_batch = %d, ret = %d\n", i, n_batch, ret);
  2796. continue; // continue loop of n_batch
  2797. }
  2798. for (auto & slot : slots) {
  2799. if (slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens)) {
  2800. continue; // continue loop of slots
  2801. }
  2802. if (slot.state == SLOT_STATE_DONE_PROMPT) {
  2803. if (slot.task_type == SERVER_TASK_TYPE_EMBEDDING) {
  2804. // prompt evaluated for embedding
  2805. send_embedding(slot, batch_view);
  2806. slot.release();
  2807. slot.i_batch = -1;
  2808. continue; // continue loop of slots
  2809. }
  2810. if (slot.task_type == SERVER_TASK_TYPE_RERANK) {
  2811. send_rerank(slot, batch_view);
  2812. slot.release();
  2813. slot.i_batch = -1;
  2814. continue; // continue loop of slots
  2815. }
  2816. // prompt evaluated for next-token prediction
  2817. slot.state = SLOT_STATE_GENERATING;
  2818. } else if (slot.state != SLOT_STATE_GENERATING) {
  2819. continue; // continue loop of slots
  2820. }
  2821. const int tok_idx = slot.i_batch - i;
  2822. llama_token id = common_sampler_sample(slot.smpl, ctx, tok_idx);
  2823. slot.i_batch = -1;
  2824. common_sampler_accept(slot.smpl, id, true);
  2825. slot.n_decoded += 1;
  2826. const int64_t t_current = ggml_time_us();
  2827. if (slot.n_decoded == 1) {
  2828. slot.t_start_generation = t_current;
  2829. slot.t_prompt_processing = (slot.t_start_generation - slot.t_start_process_prompt) / 1e3;
  2830. metrics.on_prompt_eval(slot);
  2831. }
  2832. slot.t_token_generation = (t_current - slot.t_start_generation) / 1e3;
  2833. completion_token_output result;
  2834. result.tok = id;
  2835. result.text_to_send = common_token_to_piece(ctx, result.tok, accept_special_token(slot, result.tok));
  2836. result.prob = 1.0f; // TODO: set it here instead of doing inside populate_token_probs
  2837. if (slot.params.sampling.n_probs > 0) {
  2838. populate_token_probs(slot, result, slot.params.post_sampling_probs, params_base.special, tok_idx);
  2839. }
  2840. if (!process_token(result, slot)) {
  2841. // release slot because of stop condition
  2842. slot.release();
  2843. slot.print_timings();
  2844. send_final_response(slot);
  2845. metrics.on_prediction(slot);
  2846. continue;
  2847. }
  2848. }
  2849. // do speculative decoding
  2850. for (auto & slot : slots) {
  2851. if (!slot.is_processing() || !slot.can_speculate()) {
  2852. continue;
  2853. }
  2854. if (slot.state != SLOT_STATE_GENERATING) {
  2855. continue;
  2856. }
  2857. if (mctx) {
  2858. // we should never reach this, as speculative is automatically disabled if mmproj is loaded
  2859. GGML_ABORT("not supported by multimodal");
  2860. }
  2861. // determine the max draft that fits the current slot state
  2862. int n_draft_max = slot.params.speculative.n_max;
  2863. // note: n_past is not yet increased for the `id` token sampled above
  2864. // also, need to leave space for 1 extra token to allow context shifts
  2865. n_draft_max = std::min(n_draft_max, slot.n_ctx - slot.n_past - 2);
  2866. if (slot.n_remaining > 0) {
  2867. n_draft_max = std::min(n_draft_max, slot.n_remaining - 1);
  2868. }
  2869. SLT_DBG(slot, "max possible draft: %d\n", n_draft_max);
  2870. if (n_draft_max < slot.params.speculative.n_min) {
  2871. SLT_DBG(slot, "the max possible draft is too small: %d < %d - skipping speculative decoding\n", n_draft_max, slot.params.speculative.n_min);
  2872. continue;
  2873. }
  2874. llama_token id = slot.sampled;
  2875. struct common_speculative_params params_spec;
  2876. params_spec.n_draft = n_draft_max;
  2877. params_spec.n_reuse = llama_n_ctx(slot.ctx_dft) - slot.params.speculative.n_max;
  2878. params_spec.p_min = slot.params.speculative.p_min;
  2879. const llama_tokens & cached_text_tokens = slot.cache_tokens.get_text_tokens();
  2880. llama_tokens draft = common_speculative_gen_draft(slot.spec, params_spec, cached_text_tokens, id);
  2881. // keep track of total number of tokens generated in the draft
  2882. slot.n_draft_total += draft.size();
  2883. // ignore small drafts
  2884. if (slot.params.speculative.n_min > (int) draft.size()) {
  2885. SLT_DBG(slot, "ignoring small draft: %d < %d\n", (int) draft.size(), slot.params.speculative.n_min);
  2886. continue;
  2887. }
  2888. // construct the speculation batch
  2889. common_batch_clear(slot.batch_spec);
  2890. common_batch_add (slot.batch_spec, id, slot.n_past, { slot.id }, true);
  2891. for (size_t i = 0; i < draft.size(); ++i) {
  2892. common_batch_add(slot.batch_spec, draft[i], slot.n_past + 1 + i, { slot.id }, true);
  2893. }
  2894. SLT_DBG(slot, "decoding speculative batch, size = %d\n", slot.batch_spec.n_tokens);
  2895. llama_decode(ctx, slot.batch_spec);
  2896. // the accepted tokens from the speculation
  2897. const auto ids = common_sampler_sample_and_accept_n(slot.smpl, ctx, draft);
  2898. slot.n_past += ids.size();
  2899. slot.n_decoded += ids.size();
  2900. // update how many tokens out of draft was accepted
  2901. slot.n_draft_accepted += ids.size() - 1;
  2902. slot.cache_tokens.push_back(id);
  2903. slot.cache_tokens.insert({ids.begin(), ids.end() - 1});
  2904. llama_kv_self_seq_rm(ctx, slot.id, slot.n_past, -1);
  2905. for (size_t i = 0; i < ids.size(); ++i) {
  2906. completion_token_output result;
  2907. result.tok = ids[i];
  2908. result.text_to_send = common_token_to_piece(ctx, result.tok, accept_special_token(slot, result.tok));
  2909. result.prob = 1.0f; // set later
  2910. // TODO: set result.probs
  2911. if (!process_token(result, slot)) {
  2912. // release slot because of stop condition
  2913. slot.release();
  2914. slot.print_timings();
  2915. send_final_response(slot);
  2916. metrics.on_prediction(slot);
  2917. break;
  2918. }
  2919. }
  2920. SLT_DBG(slot, "accepted %d/%d draft tokens, new n_past = %d\n", (int) ids.size() - 1, (int) draft.size(), slot.n_past);
  2921. }
  2922. }
  2923. SRV_DBG("%s", "run slots completed\n");
  2924. }
  2925. json model_meta() const {
  2926. return json {
  2927. {"vocab_type", llama_vocab_type (vocab)},
  2928. {"n_vocab", llama_vocab_n_tokens (vocab)},
  2929. {"n_ctx_train", llama_model_n_ctx_train(model)},
  2930. {"n_embd", llama_model_n_embd (model)},
  2931. {"n_params", llama_model_n_params (model)},
  2932. {"size", llama_model_size (model)},
  2933. };
  2934. }
  2935. };
  2936. static void log_server_request(const httplib::Request & req, const httplib::Response & res) {
  2937. // skip GH copilot requests when using default port
  2938. if (req.path == "/v1/health" || req.path == "/v1/completions") {
  2939. return;
  2940. }
  2941. // reminder: this function is not covered by httplib's exception handler; if someone does more complicated stuff, think about wrapping it in try-catch
  2942. SRV_INF("request: %s %s %s %d\n", req.method.c_str(), req.path.c_str(), req.remote_addr.c_str(), res.status);
  2943. SRV_DBG("request: %s\n", req.body.c_str());
  2944. SRV_DBG("response: %s\n", res.body.c_str());
  2945. }
  2946. std::function<void(int)> shutdown_handler;
  2947. std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
  2948. inline void signal_handler(int signal) {
  2949. if (is_terminating.test_and_set()) {
  2950. // in case it hangs, we can force terminate the server by hitting Ctrl+C twice
  2951. // this is for better developer experience, we can remove when the server is stable enough
  2952. fprintf(stderr, "Received second interrupt, terminating immediately.\n");
  2953. exit(1);
  2954. }
  2955. shutdown_handler(signal);
  2956. }
  2957. int main(int argc, char ** argv) {
  2958. // own arguments required by this example
  2959. common_params params;
  2960. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_SERVER)) {
  2961. return 1;
  2962. }
  2963. common_init();
  2964. // struct that contains llama context and inference
  2965. server_context ctx_server;
  2966. llama_backend_init();
  2967. llama_numa_init(params.numa);
  2968. LOG_INF("system info: n_threads = %d, n_threads_batch = %d, total_threads = %d\n", params.cpuparams.n_threads, params.cpuparams_batch.n_threads, std::thread::hardware_concurrency());
  2969. LOG_INF("\n");
  2970. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  2971. LOG_INF("\n");
  2972. std::unique_ptr<httplib::Server> svr;
  2973. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2974. if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
  2975. LOG_INF("Running with SSL: key = %s, cert = %s\n", params.ssl_file_key.c_str(), params.ssl_file_cert.c_str());
  2976. svr.reset(
  2977. new httplib::SSLServer(params.ssl_file_cert.c_str(), params.ssl_file_key.c_str())
  2978. );
  2979. } else {
  2980. LOG_INF("Running without SSL\n");
  2981. svr.reset(new httplib::Server());
  2982. }
  2983. #else
  2984. if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
  2985. LOG_ERR("Server is built without SSL support\n");
  2986. return 1;
  2987. }
  2988. svr.reset(new httplib::Server());
  2989. #endif
  2990. std::atomic<server_state> state{SERVER_STATE_LOADING_MODEL};
  2991. svr->set_default_headers({{"Server", "llama.cpp"}});
  2992. svr->set_logger(log_server_request);
  2993. auto res_error = [](httplib::Response & res, const json & error_data) {
  2994. json final_response {{"error", error_data}};
  2995. res.set_content(safe_json_to_str(final_response), MIMETYPE_JSON);
  2996. res.status = json_value(error_data, "code", 500);
  2997. };
  2998. auto res_ok = [](httplib::Response & res, const json & data) {
  2999. res.set_content(safe_json_to_str(data), MIMETYPE_JSON);
  3000. res.status = 200;
  3001. };
  3002. svr->set_exception_handler([&res_error](const httplib::Request &, httplib::Response & res, const std::exception_ptr & ep) {
  3003. std::string message;
  3004. try {
  3005. std::rethrow_exception(ep);
  3006. } catch (const std::exception & e) {
  3007. message = e.what();
  3008. } catch (...) {
  3009. message = "Unknown Exception";
  3010. }
  3011. try {
  3012. json formatted_error = format_error_response(message, ERROR_TYPE_SERVER);
  3013. LOG_WRN("got exception: %s\n", formatted_error.dump().c_str());
  3014. res_error(res, formatted_error);
  3015. } catch (const std::exception & e) {
  3016. LOG_ERR("got another exception: %s | while hanlding exception: %s\n", e.what(), message.c_str());
  3017. }
  3018. });
  3019. svr->set_error_handler([&res_error](const httplib::Request &, httplib::Response & res) {
  3020. if (res.status == 404) {
  3021. res_error(res, format_error_response("File Not Found", ERROR_TYPE_NOT_FOUND));
  3022. }
  3023. // for other error codes, we skip processing here because it's already done by res_error()
  3024. });
  3025. // set timeouts and change hostname and port
  3026. svr->set_read_timeout (params.timeout_read);
  3027. svr->set_write_timeout(params.timeout_write);
  3028. std::unordered_map<std::string, std::string> log_data;
  3029. log_data["hostname"] = params.hostname;
  3030. log_data["port"] = std::to_string(params.port);
  3031. if (params.api_keys.size() == 1) {
  3032. auto key = params.api_keys[0];
  3033. log_data["api_key"] = "api_key: ****" + key.substr(std::max((int)(key.length() - 4), 0));
  3034. } else if (params.api_keys.size() > 1) {
  3035. log_data["api_key"] = "api_key: " + std::to_string(params.api_keys.size()) + " keys loaded";
  3036. }
  3037. // Necessary similarity of prompt for slot selection
  3038. ctx_server.slot_prompt_similarity = params.slot_prompt_similarity;
  3039. //
  3040. // Middlewares
  3041. //
  3042. auto middleware_validate_api_key = [&params, &res_error](const httplib::Request & req, httplib::Response & res) {
  3043. static const std::unordered_set<std::string> public_endpoints = {
  3044. "/health",
  3045. "/models",
  3046. "/v1/models",
  3047. };
  3048. // If API key is not set, skip validation
  3049. if (params.api_keys.empty()) {
  3050. return true;
  3051. }
  3052. // If path is public or is static file, skip validation
  3053. if (public_endpoints.find(req.path) != public_endpoints.end() || req.path == "/") {
  3054. return true;
  3055. }
  3056. // Check for API key in the header
  3057. auto auth_header = req.get_header_value("Authorization");
  3058. std::string prefix = "Bearer ";
  3059. if (auth_header.substr(0, prefix.size()) == prefix) {
  3060. std::string received_api_key = auth_header.substr(prefix.size());
  3061. if (std::find(params.api_keys.begin(), params.api_keys.end(), received_api_key) != params.api_keys.end()) {
  3062. return true; // API key is valid
  3063. }
  3064. }
  3065. // API key is invalid or not provided
  3066. res_error(res, format_error_response("Invalid API Key", ERROR_TYPE_AUTHENTICATION));
  3067. LOG_WRN("Unauthorized: Invalid API Key\n");
  3068. return false;
  3069. };
  3070. auto middleware_server_state = [&res_error, &state](const httplib::Request & req, httplib::Response & res) {
  3071. server_state current_state = state.load();
  3072. if (current_state == SERVER_STATE_LOADING_MODEL) {
  3073. auto tmp = string_split<std::string>(req.path, '.');
  3074. if (req.path == "/" || tmp.back() == "html") {
  3075. res.set_content(reinterpret_cast<const char*>(loading_html), loading_html_len, "text/html; charset=utf-8");
  3076. res.status = 503;
  3077. } else if (req.path == "/models" || req.path == "/v1/models") {
  3078. // allow the models endpoint to be accessed during loading
  3079. return true;
  3080. } else {
  3081. res_error(res, format_error_response("Loading model", ERROR_TYPE_UNAVAILABLE));
  3082. }
  3083. return false;
  3084. }
  3085. return true;
  3086. };
  3087. // register server middlewares
  3088. svr->set_pre_routing_handler([&middleware_validate_api_key, &middleware_server_state](const httplib::Request & req, httplib::Response & res) {
  3089. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  3090. // If this is OPTIONS request, skip validation because browsers don't include Authorization header
  3091. if (req.method == "OPTIONS") {
  3092. res.set_header("Access-Control-Allow-Credentials", "true");
  3093. res.set_header("Access-Control-Allow-Methods", "GET, POST");
  3094. res.set_header("Access-Control-Allow-Headers", "*");
  3095. res.set_content("", "text/html"); // blank response, no data
  3096. return httplib::Server::HandlerResponse::Handled; // skip further processing
  3097. }
  3098. if (!middleware_server_state(req, res)) {
  3099. return httplib::Server::HandlerResponse::Handled;
  3100. }
  3101. if (!middleware_validate_api_key(req, res)) {
  3102. return httplib::Server::HandlerResponse::Handled;
  3103. }
  3104. return httplib::Server::HandlerResponse::Unhandled;
  3105. });
  3106. //
  3107. // Route handlers (or controllers)
  3108. //
  3109. const auto handle_health = [&](const httplib::Request &, httplib::Response & res) {
  3110. // error and loading states are handled by middleware
  3111. json health = {{"status", "ok"}};
  3112. res_ok(res, health);
  3113. };
  3114. const auto handle_slots = [&](const httplib::Request & req, httplib::Response & res) {
  3115. if (!params.endpoint_slots) {
  3116. res_error(res, format_error_response("This server does not support slots endpoint. Start it with `--slots`", ERROR_TYPE_NOT_SUPPORTED));
  3117. return;
  3118. }
  3119. // request slots data using task queue
  3120. int task_id = ctx_server.queue_tasks.get_new_id();
  3121. {
  3122. server_task task(SERVER_TASK_TYPE_METRICS);
  3123. task.id = task_id;
  3124. ctx_server.queue_results.add_waiting_task_id(task_id);
  3125. ctx_server.queue_tasks.post(std::move(task), true); // high-priority task
  3126. }
  3127. // get the result
  3128. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  3129. ctx_server.queue_results.remove_waiting_task_id(task_id);
  3130. if (result->is_error()) {
  3131. res_error(res, result->to_json());
  3132. return;
  3133. }
  3134. // TODO: get rid of this dynamic_cast
  3135. auto res_metrics = dynamic_cast<server_task_result_metrics*>(result.get());
  3136. GGML_ASSERT(res_metrics != nullptr);
  3137. // optionally return "fail_on_no_slot" error
  3138. if (req.has_param("fail_on_no_slot")) {
  3139. if (res_metrics->n_idle_slots == 0) {
  3140. res_error(res, format_error_response("no slot available", ERROR_TYPE_UNAVAILABLE));
  3141. return;
  3142. }
  3143. }
  3144. res_ok(res, res_metrics->slots_data);
  3145. };
  3146. const auto handle_metrics = [&](const httplib::Request &, httplib::Response & res) {
  3147. if (!params.endpoint_metrics) {
  3148. res_error(res, format_error_response("This server does not support metrics endpoint. Start it with `--metrics`", ERROR_TYPE_NOT_SUPPORTED));
  3149. return;
  3150. }
  3151. // request slots data using task queue
  3152. int task_id = ctx_server.queue_tasks.get_new_id();
  3153. {
  3154. server_task task(SERVER_TASK_TYPE_METRICS);
  3155. task.id = task_id;
  3156. ctx_server.queue_results.add_waiting_task_id(task_id);
  3157. ctx_server.queue_tasks.post(std::move(task), true); // high-priority task
  3158. }
  3159. // get the result
  3160. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  3161. ctx_server.queue_results.remove_waiting_task_id(task_id);
  3162. if (result->is_error()) {
  3163. res_error(res, result->to_json());
  3164. return;
  3165. }
  3166. // TODO: get rid of this dynamic_cast
  3167. auto res_metrics = dynamic_cast<server_task_result_metrics*>(result.get());
  3168. GGML_ASSERT(res_metrics != nullptr);
  3169. // metrics definition: https://prometheus.io/docs/practices/naming/#metric-names
  3170. json all_metrics_def = json {
  3171. {"counter", {{
  3172. {"name", "prompt_tokens_total"},
  3173. {"help", "Number of prompt tokens processed."},
  3174. {"value", (uint64_t) res_metrics->n_prompt_tokens_processed_total}
  3175. }, {
  3176. {"name", "prompt_seconds_total"},
  3177. {"help", "Prompt process time"},
  3178. {"value", (uint64_t) res_metrics->t_prompt_processing_total / 1.e3}
  3179. }, {
  3180. {"name", "tokens_predicted_total"},
  3181. {"help", "Number of generation tokens processed."},
  3182. {"value", (uint64_t) res_metrics->n_tokens_predicted_total}
  3183. }, {
  3184. {"name", "tokens_predicted_seconds_total"},
  3185. {"help", "Predict process time"},
  3186. {"value", (uint64_t) res_metrics->t_tokens_generation_total / 1.e3}
  3187. }, {
  3188. {"name", "n_decode_total"},
  3189. {"help", "Total number of llama_decode() calls"},
  3190. {"value", res_metrics->n_decode_total}
  3191. }, {
  3192. {"name", "n_busy_slots_per_decode"},
  3193. {"help", "Average number of busy slots per llama_decode() call"},
  3194. {"value", (float) res_metrics->n_busy_slots_total / std::max((float) res_metrics->n_decode_total, 1.f)}
  3195. }}},
  3196. {"gauge", {{
  3197. {"name", "prompt_tokens_seconds"},
  3198. {"help", "Average prompt throughput in tokens/s."},
  3199. {"value", res_metrics->n_prompt_tokens_processed ? 1.e3 / res_metrics->t_prompt_processing * res_metrics->n_prompt_tokens_processed : 0.}
  3200. },{
  3201. {"name", "predicted_tokens_seconds"},
  3202. {"help", "Average generation throughput in tokens/s."},
  3203. {"value", res_metrics->n_tokens_predicted ? 1.e3 / res_metrics->t_tokens_generation * res_metrics->n_tokens_predicted : 0.}
  3204. },{
  3205. {"name", "requests_processing"},
  3206. {"help", "Number of requests processing."},
  3207. {"value", (uint64_t) res_metrics->n_processing_slots}
  3208. },{
  3209. {"name", "requests_deferred"},
  3210. {"help", "Number of requests deferred."},
  3211. {"value", (uint64_t) res_metrics->n_tasks_deferred}
  3212. }}}
  3213. };
  3214. std::stringstream prometheus;
  3215. for (const auto & el : all_metrics_def.items()) {
  3216. const auto & type = el.key();
  3217. const auto & metrics_def = el.value();
  3218. for (const auto & metric_def : metrics_def) {
  3219. const std::string name = metric_def.at("name");
  3220. const std::string help = metric_def.at("help");
  3221. auto value = json_value(metric_def, "value", 0.);
  3222. prometheus << "# HELP llamacpp:" << name << " " << help << "\n"
  3223. << "# TYPE llamacpp:" << name << " " << type << "\n"
  3224. << "llamacpp:" << name << " " << value << "\n";
  3225. }
  3226. }
  3227. res.set_header("Process-Start-Time-Unix", std::to_string(res_metrics->t_start));
  3228. res.set_content(prometheus.str(), "text/plain; version=0.0.4");
  3229. res.status = 200; // HTTP OK
  3230. };
  3231. const auto handle_slots_save = [&ctx_server, &res_error, &res_ok, &params](const httplib::Request & req, httplib::Response & res, int id_slot) {
  3232. json request_data = json::parse(req.body);
  3233. std::string filename = request_data.at("filename");
  3234. if (!fs_validate_filename(filename)) {
  3235. res_error(res, format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  3236. return;
  3237. }
  3238. std::string filepath = params.slot_save_path + filename;
  3239. int task_id = ctx_server.queue_tasks.get_new_id();
  3240. {
  3241. server_task task(SERVER_TASK_TYPE_SLOT_SAVE);
  3242. task.id = task_id;
  3243. task.slot_action.slot_id = id_slot;
  3244. task.slot_action.filename = filename;
  3245. task.slot_action.filepath = filepath;
  3246. ctx_server.queue_results.add_waiting_task_id(task_id);
  3247. ctx_server.queue_tasks.post(std::move(task));
  3248. }
  3249. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  3250. ctx_server.queue_results.remove_waiting_task_id(task_id);
  3251. if (result->is_error()) {
  3252. res_error(res, result->to_json());
  3253. return;
  3254. }
  3255. res_ok(res, result->to_json());
  3256. };
  3257. const auto handle_slots_restore = [&ctx_server, &res_error, &res_ok, &params](const httplib::Request & req, httplib::Response & res, int id_slot) {
  3258. json request_data = json::parse(req.body);
  3259. std::string filename = request_data.at("filename");
  3260. if (!fs_validate_filename(filename)) {
  3261. res_error(res, format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  3262. return;
  3263. }
  3264. std::string filepath = params.slot_save_path + filename;
  3265. int task_id = ctx_server.queue_tasks.get_new_id();
  3266. {
  3267. server_task task(SERVER_TASK_TYPE_SLOT_RESTORE);
  3268. task.id = task_id;
  3269. task.slot_action.slot_id = id_slot;
  3270. task.slot_action.filename = filename;
  3271. task.slot_action.filepath = filepath;
  3272. ctx_server.queue_results.add_waiting_task_id(task_id);
  3273. ctx_server.queue_tasks.post(std::move(task));
  3274. }
  3275. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  3276. ctx_server.queue_results.remove_waiting_task_id(task_id);
  3277. if (result->is_error()) {
  3278. res_error(res, result->to_json());
  3279. return;
  3280. }
  3281. GGML_ASSERT(dynamic_cast<server_task_result_slot_save_load*>(result.get()) != nullptr);
  3282. res_ok(res, result->to_json());
  3283. };
  3284. const auto handle_slots_erase = [&ctx_server, &res_error, &res_ok](const httplib::Request & /* req */, httplib::Response & res, int id_slot) {
  3285. int task_id = ctx_server.queue_tasks.get_new_id();
  3286. {
  3287. server_task task(SERVER_TASK_TYPE_SLOT_ERASE);
  3288. task.id = task_id;
  3289. task.slot_action.slot_id = id_slot;
  3290. ctx_server.queue_results.add_waiting_task_id(task_id);
  3291. ctx_server.queue_tasks.post(std::move(task));
  3292. }
  3293. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  3294. ctx_server.queue_results.remove_waiting_task_id(task_id);
  3295. if (result->is_error()) {
  3296. res_error(res, result->to_json());
  3297. return;
  3298. }
  3299. GGML_ASSERT(dynamic_cast<server_task_result_slot_erase*>(result.get()) != nullptr);
  3300. res_ok(res, result->to_json());
  3301. };
  3302. const auto handle_slots_action = [&params, &res_error, &handle_slots_save, &handle_slots_restore, &handle_slots_erase](const httplib::Request & req, httplib::Response & res) {
  3303. if (params.slot_save_path.empty()) {
  3304. res_error(res, format_error_response("This server does not support slots action. Start it with `--slot-save-path`", ERROR_TYPE_NOT_SUPPORTED));
  3305. return;
  3306. }
  3307. std::string id_slot_str = req.path_params.at("id_slot");
  3308. int id_slot;
  3309. try {
  3310. id_slot = std::stoi(id_slot_str);
  3311. } catch (const std::exception &) {
  3312. res_error(res, format_error_response("Invalid slot ID", ERROR_TYPE_INVALID_REQUEST));
  3313. return;
  3314. }
  3315. std::string action = req.get_param_value("action");
  3316. if (action == "save") {
  3317. handle_slots_save(req, res, id_slot);
  3318. } else if (action == "restore") {
  3319. handle_slots_restore(req, res, id_slot);
  3320. } else if (action == "erase") {
  3321. handle_slots_erase(req, res, id_slot);
  3322. } else {
  3323. res_error(res, format_error_response("Invalid action", ERROR_TYPE_INVALID_REQUEST));
  3324. }
  3325. };
  3326. const auto handle_props = [&ctx_server, &res_ok](const httplib::Request &, httplib::Response & res) {
  3327. // this endpoint is publicly available, please only return what is safe to be exposed
  3328. json data = {
  3329. { "default_generation_settings", ctx_server.default_generation_settings_for_props },
  3330. { "total_slots", ctx_server.params_base.n_parallel },
  3331. { "model_path", ctx_server.params_base.model.path },
  3332. { "modalities", json{{"vision", ctx_server.mctx != nullptr}} }, // TODO: add more in the future
  3333. { "chat_template", common_chat_templates_source(ctx_server.chat_templates.get()) },
  3334. { "bos_token", common_token_to_piece(ctx_server.ctx, llama_vocab_bos(ctx_server.vocab), /* special= */ true)},
  3335. { "eos_token", common_token_to_piece(ctx_server.ctx, llama_vocab_eos(ctx_server.vocab), /* special= */ true)},
  3336. { "build_info", build_info },
  3337. };
  3338. if (ctx_server.params_base.use_jinja) {
  3339. if (auto tool_use_src = common_chat_templates_source(ctx_server.chat_templates.get(), "tool_use")) {
  3340. data["chat_template_tool_use"] = tool_use_src;
  3341. }
  3342. }
  3343. res_ok(res, data);
  3344. };
  3345. const auto handle_props_change = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  3346. if (!ctx_server.params_base.endpoint_props) {
  3347. res_error(res, format_error_response("This server does not support changing global properties. Start it with `--props`", ERROR_TYPE_NOT_SUPPORTED));
  3348. return;
  3349. }
  3350. json data = json::parse(req.body);
  3351. // update any props here
  3352. res_ok(res, {{ "success", true }});
  3353. };
  3354. const auto handle_api_show = [&ctx_server, &res_ok](const httplib::Request &, httplib::Response & res) {
  3355. json data = {
  3356. {
  3357. "template", common_chat_templates_source(ctx_server.chat_templates.get()),
  3358. },
  3359. {
  3360. "model_info", {
  3361. { "llama.context_length", ctx_server.slots.back().n_ctx, },
  3362. }
  3363. },
  3364. };
  3365. res_ok(res, data);
  3366. };
  3367. // handle completion-like requests (completion, chat, infill)
  3368. // we can optionally provide a custom format for partial results and final results
  3369. const auto handle_completions_impl = [&ctx_server, &res_error, &res_ok](
  3370. server_task_type type,
  3371. json & data,
  3372. const std::vector<raw_buffer> & files,
  3373. const std::function<bool()> & is_connection_closed,
  3374. httplib::Response & res,
  3375. oaicompat_type oaicompat) -> void {
  3376. GGML_ASSERT(type == SERVER_TASK_TYPE_COMPLETION || type == SERVER_TASK_TYPE_INFILL);
  3377. if (ctx_server.params_base.embedding) {
  3378. res_error(res, format_error_response("This server does not support completions. Start it without `--embeddings`", ERROR_TYPE_NOT_SUPPORTED));
  3379. return;
  3380. }
  3381. auto completion_id = gen_chatcmplid();
  3382. std::unordered_set<int> task_ids;
  3383. try {
  3384. std::vector<server_task> tasks;
  3385. const auto & prompt = data.at("prompt");
  3386. // TODO: this log can become very long, put it behind a flag or think about a more compact format
  3387. //SRV_DBG("Prompt: %s\n", prompt.is_string() ? prompt.get<std::string>().c_str() : prompt.dump(2).c_str());
  3388. // process files
  3389. mtmd::bitmaps bitmaps;
  3390. const bool has_mtmd = ctx_server.mctx != nullptr;
  3391. {
  3392. if (!has_mtmd && !files.empty()) {
  3393. throw std::runtime_error("This server does not support multimodal");
  3394. }
  3395. for (auto & file : files) {
  3396. mtmd::bitmap bmp(mtmd_helper_bitmap_init_from_buf(file.data(), file.size()));
  3397. if (!bmp.ptr) {
  3398. throw std::runtime_error("Failed to load image");
  3399. }
  3400. // calculate bitmap hash (for KV caching)
  3401. std::string hash = fnv_hash(bmp.data(), bmp.nx()*bmp.ny()*3);
  3402. bmp.set_id(hash.c_str());
  3403. bitmaps.entries.push_back(std::move(bmp));
  3404. }
  3405. }
  3406. // process prompt
  3407. std::vector<server_tokens> inputs;
  3408. if (oaicompat && !prompt.is_string()) {
  3409. throw std::runtime_error("prompt must be a string");
  3410. }
  3411. if (oaicompat && has_mtmd) {
  3412. // multimodal
  3413. std::string prompt_str = prompt.get<std::string>();
  3414. mtmd_input_text inp_txt = {
  3415. prompt_str.c_str(),
  3416. /* add_special */ true,
  3417. /* parse_special */ true,
  3418. };
  3419. mtmd::input_chunks chunks(mtmd_input_chunks_init());
  3420. auto bitmaps_c_ptr = bitmaps.c_ptr();
  3421. int32_t tokenized = mtmd_tokenize(ctx_server.mctx,
  3422. chunks.ptr.get(),
  3423. &inp_txt,
  3424. bitmaps_c_ptr.data(),
  3425. bitmaps_c_ptr.size());
  3426. if (tokenized != 0) {
  3427. throw std::runtime_error("Failed to tokenize prompt");
  3428. }
  3429. server_tokens tmp(chunks, true);
  3430. inputs.push_back(std::move(tmp));
  3431. } else {
  3432. // non-multimodal version
  3433. auto tokenized_prompts = tokenize_input_prompts(ctx_server.vocab, prompt, true, true);
  3434. for (auto & p : tokenized_prompts) {
  3435. auto tmp = server_tokens(p, ctx_server.mctx != nullptr);
  3436. inputs.push_back(std::move(tmp));
  3437. }
  3438. }
  3439. tasks.reserve(inputs.size());
  3440. for (size_t i = 0; i < inputs.size(); i++) {
  3441. server_task task = server_task(type);
  3442. task.id = ctx_server.queue_tasks.get_new_id();
  3443. task.index = i;
  3444. task.prompt_tokens = std::move(inputs[i]);
  3445. task.params = server_task::params_from_json_cmpl(
  3446. ctx_server.ctx,
  3447. ctx_server.params_base,
  3448. data);
  3449. task.id_selected_slot = json_value(data, "id_slot", -1);
  3450. // OAI-compat
  3451. task.params.oaicompat = oaicompat;
  3452. task.params.oaicompat_cmpl_id = completion_id;
  3453. // oaicompat_model is already populated by params_from_json_cmpl
  3454. tasks.push_back(std::move(task));
  3455. }
  3456. task_ids = server_task::get_list_id(tasks);
  3457. ctx_server.queue_results.add_waiting_tasks(tasks);
  3458. ctx_server.queue_tasks.post(std::move(tasks));
  3459. } catch (const std::exception & e) {
  3460. res_error(res, format_error_response(e.what(), ERROR_TYPE_INVALID_REQUEST));
  3461. return;
  3462. }
  3463. bool stream = json_value(data, "stream", false);
  3464. if (!stream) {
  3465. ctx_server.receive_multi_results(task_ids, [&](std::vector<server_task_result_ptr> & results) {
  3466. if (results.size() == 1) {
  3467. // single result
  3468. res_ok(res, results[0]->to_json());
  3469. } else {
  3470. // multiple results (multitask)
  3471. json arr = json::array();
  3472. for (auto & res : results) {
  3473. arr.push_back(res->to_json());
  3474. }
  3475. res_ok(res, arr);
  3476. }
  3477. }, [&](const json & error_data) {
  3478. res_error(res, error_data);
  3479. }, is_connection_closed);
  3480. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  3481. } else {
  3482. const auto chunked_content_provider = [task_ids, &ctx_server, oaicompat](size_t, httplib::DataSink & sink) {
  3483. ctx_server.receive_cmpl_results_stream(task_ids, [&](server_task_result_ptr & result) -> bool {
  3484. json res_json = result->to_json();
  3485. if (res_json.is_array()) {
  3486. for (const auto & res : res_json) {
  3487. if (!server_sent_event(sink, "data", res)) {
  3488. // sending failed (HTTP connection closed), cancel the generation
  3489. return false;
  3490. }
  3491. }
  3492. return true;
  3493. } else {
  3494. return server_sent_event(sink, "data", res_json);
  3495. }
  3496. }, [&](const json & error_data) {
  3497. server_sent_event(sink, "error", error_data);
  3498. }, [&sink]() {
  3499. // note: do not use req.is_connection_closed here because req is already destroyed
  3500. return !sink.is_writable();
  3501. });
  3502. if (oaicompat != OAICOMPAT_TYPE_NONE) {
  3503. static const std::string ev_done = "data: [DONE]\n\n";
  3504. sink.write(ev_done.data(), ev_done.size());
  3505. }
  3506. sink.done();
  3507. return false;
  3508. };
  3509. auto on_complete = [task_ids, &ctx_server] (bool) {
  3510. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  3511. };
  3512. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  3513. }
  3514. };
  3515. const auto handle_completions = [&handle_completions_impl](const httplib::Request & req, httplib::Response & res) {
  3516. json data = json::parse(req.body);
  3517. std::vector<raw_buffer> files; // dummy
  3518. handle_completions_impl(
  3519. SERVER_TASK_TYPE_COMPLETION,
  3520. data,
  3521. files,
  3522. req.is_connection_closed,
  3523. res,
  3524. OAICOMPAT_TYPE_NONE);
  3525. };
  3526. const auto handle_completions_oai = [&handle_completions_impl](const httplib::Request & req, httplib::Response & res) {
  3527. json data = oaicompat_completion_params_parse(json::parse(req.body));
  3528. std::vector<raw_buffer> files; // dummy
  3529. handle_completions_impl(
  3530. SERVER_TASK_TYPE_COMPLETION,
  3531. data,
  3532. files,
  3533. req.is_connection_closed,
  3534. res,
  3535. OAICOMPAT_TYPE_COMPLETION);
  3536. };
  3537. const auto handle_infill = [&ctx_server, &res_error, &handle_completions_impl](const httplib::Request & req, httplib::Response & res) {
  3538. // check model compatibility
  3539. std::string err;
  3540. if (llama_vocab_fim_pre(ctx_server.vocab) == LLAMA_TOKEN_NULL) {
  3541. err += "prefix token is missing. ";
  3542. }
  3543. if (llama_vocab_fim_suf(ctx_server.vocab) == LLAMA_TOKEN_NULL) {
  3544. err += "suffix token is missing. ";
  3545. }
  3546. if (llama_vocab_fim_mid(ctx_server.vocab) == LLAMA_TOKEN_NULL) {
  3547. err += "middle token is missing. ";
  3548. }
  3549. if (!err.empty()) {
  3550. res_error(res, format_error_response(string_format("Infill is not supported by this model: %s", err.c_str()), ERROR_TYPE_NOT_SUPPORTED));
  3551. return;
  3552. }
  3553. json data = json::parse(req.body);
  3554. // validate input
  3555. if (data.contains("prompt") && !data.at("prompt").is_string()) {
  3556. // prompt is optional
  3557. res_error(res, format_error_response("\"prompt\" must be a string", ERROR_TYPE_INVALID_REQUEST));
  3558. }
  3559. if (!data.contains("input_prefix")) {
  3560. res_error(res, format_error_response("\"input_prefix\" is required", ERROR_TYPE_INVALID_REQUEST));
  3561. }
  3562. if (!data.contains("input_suffix")) {
  3563. res_error(res, format_error_response("\"input_suffix\" is required", ERROR_TYPE_INVALID_REQUEST));
  3564. }
  3565. if (data.contains("input_extra") && !data.at("input_extra").is_array()) {
  3566. // input_extra is optional
  3567. res_error(res, format_error_response("\"input_extra\" must be an array of {\"filename\": string, \"text\": string}", ERROR_TYPE_INVALID_REQUEST));
  3568. return;
  3569. }
  3570. json input_extra = json_value(data, "input_extra", json::array());
  3571. for (const auto & chunk : input_extra) {
  3572. // { "text": string, "filename": string }
  3573. if (!chunk.contains("text") || !chunk.at("text").is_string()) {
  3574. res_error(res, format_error_response("extra_context chunk must contain a \"text\" field with a string value", ERROR_TYPE_INVALID_REQUEST));
  3575. return;
  3576. }
  3577. // filename is optional
  3578. if (chunk.contains("filename") && !chunk.at("filename").is_string()) {
  3579. res_error(res, format_error_response("extra_context chunk's \"filename\" field must be a string", ERROR_TYPE_INVALID_REQUEST));
  3580. return;
  3581. }
  3582. }
  3583. data["input_extra"] = input_extra; // default to empty array if it's not exist
  3584. std::string prompt = json_value(data, "prompt", std::string());
  3585. std::vector<llama_tokens> tokenized_prompts = tokenize_input_prompts(ctx_server.vocab, prompt, false, true);
  3586. SRV_DBG("creating infill tasks, n_prompts = %d\n", (int) tokenized_prompts.size());
  3587. data["prompt"] = format_infill(
  3588. ctx_server.vocab,
  3589. data.at("input_prefix"),
  3590. data.at("input_suffix"),
  3591. data.at("input_extra"),
  3592. ctx_server.params_base.n_batch,
  3593. ctx_server.params_base.n_predict,
  3594. ctx_server.slots[0].n_ctx, // TODO: there should be a better way
  3595. ctx_server.params_base.spm_infill,
  3596. tokenized_prompts[0]
  3597. );
  3598. std::vector<raw_buffer> files; // dummy
  3599. handle_completions_impl(
  3600. SERVER_TASK_TYPE_INFILL,
  3601. data,
  3602. files,
  3603. req.is_connection_closed,
  3604. res,
  3605. OAICOMPAT_TYPE_NONE); // infill is not OAI compatible
  3606. };
  3607. const auto handle_chat_completions = [&ctx_server, &params, &res_error, &handle_completions_impl](const httplib::Request & req, httplib::Response & res) {
  3608. LOG_DBG("request: %s\n", req.body.c_str());
  3609. if (ctx_server.params_base.embedding) {
  3610. res_error(res, format_error_response("This server does not support completions. Start it without `--embeddings`", ERROR_TYPE_NOT_SUPPORTED));
  3611. return;
  3612. }
  3613. auto body = json::parse(req.body);
  3614. std::vector<raw_buffer> files;
  3615. json data = oaicompat_completion_params_parse(
  3616. body,
  3617. params.use_jinja,
  3618. params.prefill_assistant,
  3619. params.reasoning_format,
  3620. ctx_server.chat_templates.get(),
  3621. ctx_server.mctx,
  3622. files);
  3623. handle_completions_impl(
  3624. SERVER_TASK_TYPE_COMPLETION,
  3625. data,
  3626. files,
  3627. req.is_connection_closed,
  3628. res,
  3629. OAICOMPAT_TYPE_CHAT);
  3630. };
  3631. // same with handle_chat_completions, but without inference part
  3632. const auto handle_apply_template = [&ctx_server, &params, &res_ok](const httplib::Request & req, httplib::Response & res) {
  3633. auto body = json::parse(req.body);
  3634. std::vector<raw_buffer> files; // dummy, unused
  3635. json data = oaicompat_completion_params_parse(
  3636. body,
  3637. params.use_jinja,
  3638. params.prefill_assistant,
  3639. params.reasoning_format,
  3640. ctx_server.chat_templates.get(),
  3641. ctx_server.mctx,
  3642. files);
  3643. res_ok(res, {{ "prompt", std::move(data.at("prompt")) }});
  3644. };
  3645. const auto handle_models = [&params, &ctx_server, &state, &res_ok](const httplib::Request &, httplib::Response & res) {
  3646. server_state current_state = state.load();
  3647. json model_meta = nullptr;
  3648. if (current_state == SERVER_STATE_READY) {
  3649. model_meta = ctx_server.model_meta();
  3650. }
  3651. json models = {
  3652. {"object", "list"},
  3653. {"data", {
  3654. {
  3655. {"id", params.model_alias.empty() ? params.model.path : params.model_alias},
  3656. {"object", "model"},
  3657. {"created", std::time(0)},
  3658. {"owned_by", "llamacpp"},
  3659. {"meta", model_meta},
  3660. },
  3661. }}
  3662. };
  3663. res_ok(res, models);
  3664. };
  3665. const auto handle_tokenize = [&ctx_server, &res_ok](const httplib::Request & req, httplib::Response & res) {
  3666. const json body = json::parse(req.body);
  3667. json tokens_response = json::array();
  3668. if (body.count("content") != 0) {
  3669. const bool add_special = json_value(body, "add_special", false);
  3670. const bool with_pieces = json_value(body, "with_pieces", false);
  3671. llama_tokens tokens = tokenize_mixed(ctx_server.vocab, body.at("content"), add_special, true);
  3672. if (with_pieces) {
  3673. for (const auto& token : tokens) {
  3674. std::string piece = common_token_to_piece(ctx_server.ctx, token);
  3675. json piece_json;
  3676. // Check if the piece is valid UTF-8
  3677. if (is_valid_utf8(piece)) {
  3678. piece_json = piece;
  3679. } else {
  3680. // If not valid UTF-8, store as array of byte values
  3681. piece_json = json::array();
  3682. for (unsigned char c : piece) {
  3683. piece_json.push_back(static_cast<int>(c));
  3684. }
  3685. }
  3686. tokens_response.push_back({
  3687. {"id", token},
  3688. {"piece", piece_json}
  3689. });
  3690. }
  3691. } else {
  3692. tokens_response = tokens;
  3693. }
  3694. }
  3695. const json data = format_tokenizer_response(tokens_response);
  3696. res_ok(res, data);
  3697. };
  3698. const auto handle_detokenize = [&ctx_server, &res_ok](const httplib::Request & req, httplib::Response & res) {
  3699. const json body = json::parse(req.body);
  3700. std::string content;
  3701. if (body.count("tokens") != 0) {
  3702. const llama_tokens tokens = body.at("tokens");
  3703. content = tokens_to_str(ctx_server.ctx, tokens.cbegin(), tokens.cend());
  3704. }
  3705. const json data = format_detokenized_response(content);
  3706. res_ok(res, data);
  3707. };
  3708. const auto handle_embeddings_impl = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res, oaicompat_type oaicompat) {
  3709. const json body = json::parse(req.body);
  3710. if (oaicompat != OAICOMPAT_TYPE_NONE && llama_pooling_type(ctx_server.ctx) == LLAMA_POOLING_TYPE_NONE) {
  3711. res_error(res, format_error_response("Pooling type 'none' is not OAI compatible. Please use a different pooling type", ERROR_TYPE_INVALID_REQUEST));
  3712. return;
  3713. }
  3714. // for the shape of input/content, see tokenize_input_prompts()
  3715. json prompt;
  3716. if (body.count("input") != 0) {
  3717. prompt = body.at("input");
  3718. } else if (body.contains("content")) {
  3719. oaicompat = OAICOMPAT_TYPE_NONE; // "content" field is not OAI compatible
  3720. prompt = body.at("content");
  3721. } else {
  3722. res_error(res, format_error_response("\"input\" or \"content\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  3723. return;
  3724. }
  3725. bool use_base64 = false;
  3726. if (body.count("encoding_format") != 0) {
  3727. const std::string& format = body.at("encoding_format");
  3728. if (format == "base64") {
  3729. use_base64 = true;
  3730. } else if (format != "float") {
  3731. res_error(res, format_error_response("The format to return the embeddings in. Can be either float or base64", ERROR_TYPE_INVALID_REQUEST));
  3732. return;
  3733. }
  3734. }
  3735. auto tokenized_prompts = tokenize_input_prompts(ctx_server.vocab, prompt, true, true);
  3736. for (const auto & tokens : tokenized_prompts) {
  3737. // this check is necessary for models that do not add BOS token to the input
  3738. if (tokens.empty()) {
  3739. res_error(res, format_error_response("Input content cannot be empty", ERROR_TYPE_INVALID_REQUEST));
  3740. return;
  3741. }
  3742. }
  3743. // create and queue the task
  3744. json responses = json::array();
  3745. bool error = false;
  3746. std::unordered_set<int> task_ids;
  3747. {
  3748. std::vector<server_task> tasks;
  3749. for (size_t i = 0; i < tokenized_prompts.size(); i++) {
  3750. server_task task = server_task(SERVER_TASK_TYPE_EMBEDDING);
  3751. task.id = ctx_server.queue_tasks.get_new_id();
  3752. task.index = i;
  3753. task.prompt_tokens = server_tokens(tokenized_prompts[i], ctx_server.mctx != nullptr);
  3754. // OAI-compat
  3755. task.params.oaicompat = oaicompat;
  3756. tasks.push_back(std::move(task));
  3757. }
  3758. task_ids = server_task::get_list_id(tasks);
  3759. ctx_server.queue_results.add_waiting_tasks(tasks);
  3760. ctx_server.queue_tasks.post(std::move(tasks));
  3761. }
  3762. // get the result
  3763. ctx_server.receive_multi_results(task_ids, [&](std::vector<server_task_result_ptr> & results) {
  3764. for (auto & res : results) {
  3765. GGML_ASSERT(dynamic_cast<server_task_result_embd*>(res.get()) != nullptr);
  3766. responses.push_back(res->to_json());
  3767. }
  3768. }, [&](const json & error_data) {
  3769. res_error(res, error_data);
  3770. error = true;
  3771. }, req.is_connection_closed);
  3772. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  3773. if (error) {
  3774. return;
  3775. }
  3776. // write JSON response
  3777. json root = oaicompat == OAICOMPAT_TYPE_EMBEDDING
  3778. ? format_embeddings_response_oaicompat(body, responses, use_base64)
  3779. : json(responses);
  3780. res_ok(res, root);
  3781. };
  3782. const auto handle_embeddings = [&handle_embeddings_impl](const httplib::Request & req, httplib::Response & res) {
  3783. handle_embeddings_impl(req, res, OAICOMPAT_TYPE_NONE);
  3784. };
  3785. const auto handle_embeddings_oai = [&handle_embeddings_impl](const httplib::Request & req, httplib::Response & res) {
  3786. handle_embeddings_impl(req, res, OAICOMPAT_TYPE_EMBEDDING);
  3787. };
  3788. const auto handle_rerank = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  3789. if (!ctx_server.params_base.reranking || ctx_server.params_base.embedding) {
  3790. res_error(res, format_error_response("This server does not support reranking. Start it with `--reranking` and without `--embedding`", ERROR_TYPE_NOT_SUPPORTED));
  3791. return;
  3792. }
  3793. const json body = json::parse(req.body);
  3794. // TODO: implement
  3795. //int top_n = 1;
  3796. //if (body.count("top_n") != 1) {
  3797. // top_n = body.at("top_n");
  3798. //} else {
  3799. // res_error(res, format_error_response("\"top_n\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  3800. // return;
  3801. //}
  3802. // if true, use TEI API format, otherwise use Jina API format
  3803. // Jina: https://jina.ai/reranker/
  3804. // TEI: https://huggingface.github.io/text-embeddings-inference/#/Text%20Embeddings%20Inference/rerank
  3805. bool is_tei_format = body.contains("texts");
  3806. json query;
  3807. if (body.count("query") == 1) {
  3808. query = body.at("query");
  3809. if (!query.is_string()) {
  3810. res_error(res, format_error_response("\"query\" must be a string", ERROR_TYPE_INVALID_REQUEST));
  3811. return;
  3812. }
  3813. } else {
  3814. res_error(res, format_error_response("\"query\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  3815. return;
  3816. }
  3817. std::vector<std::string> documents = json_value(body, "documents",
  3818. json_value(body, "texts", std::vector<std::string>()));
  3819. if (documents.empty()) {
  3820. res_error(res, format_error_response("\"documents\" must be a non-empty string array", ERROR_TYPE_INVALID_REQUEST));
  3821. return;
  3822. }
  3823. llama_tokens tokenized_query = tokenize_input_prompts(ctx_server.vocab, query, /* add_special */ false, true)[0];
  3824. // create and queue the task
  3825. json responses = json::array();
  3826. bool error = false;
  3827. std::unordered_set<int> task_ids;
  3828. {
  3829. std::vector<server_task> tasks;
  3830. auto tokenized_docs = tokenize_input_prompts(ctx_server.vocab, documents, /* add_special */ false, true);
  3831. tasks.reserve(tokenized_docs.size());
  3832. for (size_t i = 0; i < tokenized_docs.size(); i++) {
  3833. auto tmp = format_rerank(ctx_server.vocab, tokenized_query, tokenized_docs[i]);
  3834. server_task task = server_task(SERVER_TASK_TYPE_RERANK);
  3835. task.id = ctx_server.queue_tasks.get_new_id();
  3836. task.index = i;
  3837. task.prompt_tokens = server_tokens(tmp, ctx_server.mctx != nullptr);
  3838. tasks.push_back(std::move(task));
  3839. }
  3840. task_ids = server_task::get_list_id(tasks);
  3841. ctx_server.queue_results.add_waiting_tasks(tasks);
  3842. ctx_server.queue_tasks.post(std::move(tasks));
  3843. }
  3844. ctx_server.receive_multi_results(task_ids, [&](std::vector<server_task_result_ptr> & results) {
  3845. for (auto & res : results) {
  3846. GGML_ASSERT(dynamic_cast<server_task_result_rerank*>(res.get()) != nullptr);
  3847. responses.push_back(res->to_json());
  3848. }
  3849. }, [&](const json & error_data) {
  3850. res_error(res, error_data);
  3851. error = true;
  3852. }, req.is_connection_closed);
  3853. if (error) {
  3854. return;
  3855. }
  3856. // write JSON response
  3857. json root = format_response_rerank(
  3858. body,
  3859. responses,
  3860. is_tei_format,
  3861. documents);
  3862. res_ok(res, root);
  3863. };
  3864. const auto handle_lora_adapters_list = [&](const httplib::Request &, httplib::Response & res) {
  3865. json result = json::array();
  3866. const auto & loras = ctx_server.params_base.lora_adapters;
  3867. for (size_t i = 0; i < loras.size(); ++i) {
  3868. auto & lora = loras[i];
  3869. result.push_back({
  3870. {"id", i},
  3871. {"path", lora.path},
  3872. {"scale", lora.scale},
  3873. });
  3874. }
  3875. res_ok(res, result);
  3876. res.status = 200; // HTTP OK
  3877. };
  3878. const auto handle_lora_adapters_apply = [&](const httplib::Request & req, httplib::Response & res) {
  3879. const json body = json::parse(req.body);
  3880. if (!body.is_array()) {
  3881. res_error(res, format_error_response("Request body must be an array", ERROR_TYPE_INVALID_REQUEST));
  3882. return;
  3883. }
  3884. int task_id = ctx_server.queue_tasks.get_new_id();
  3885. {
  3886. server_task task(SERVER_TASK_TYPE_SET_LORA);
  3887. task.id = task_id;
  3888. task.set_lora = parse_lora_request(ctx_server.params_base.lora_adapters, body);
  3889. ctx_server.queue_results.add_waiting_task_id(task_id);
  3890. ctx_server.queue_tasks.post(std::move(task));
  3891. }
  3892. // get the result
  3893. server_task_result_ptr result = ctx_server.queue_results.recv(task_id);
  3894. ctx_server.queue_results.remove_waiting_task_id(task_id);
  3895. if (result->is_error()) {
  3896. res_error(res, result->to_json());
  3897. return;
  3898. }
  3899. GGML_ASSERT(dynamic_cast<server_task_result_apply_lora*>(result.get()) != nullptr);
  3900. res_ok(res, result->to_json());
  3901. };
  3902. //
  3903. // Router
  3904. //
  3905. if (!params.webui) {
  3906. LOG_INF("Web UI is disabled\n");
  3907. } else {
  3908. // register static assets routes
  3909. if (!params.public_path.empty()) {
  3910. // Set the base directory for serving static files
  3911. bool is_found = svr->set_mount_point("/", params.public_path);
  3912. if (!is_found) {
  3913. LOG_ERR("%s: static assets path not found: %s\n", __func__, params.public_path.c_str());
  3914. return 1;
  3915. }
  3916. } else {
  3917. // using embedded static index.html
  3918. svr->Get("/", [](const httplib::Request & req, httplib::Response & res) {
  3919. if (req.get_header_value("Accept-Encoding").find("gzip") == std::string::npos) {
  3920. res.set_content("Error: gzip is not supported by this browser", "text/plain");
  3921. } else {
  3922. res.set_header("Content-Encoding", "gzip");
  3923. // COEP and COOP headers, required by pyodide (python interpreter)
  3924. res.set_header("Cross-Origin-Embedder-Policy", "require-corp");
  3925. res.set_header("Cross-Origin-Opener-Policy", "same-origin");
  3926. res.set_content(reinterpret_cast<const char*>(index_html_gz), index_html_gz_len, "text/html; charset=utf-8");
  3927. }
  3928. return false;
  3929. });
  3930. }
  3931. }
  3932. // register API routes
  3933. svr->Get ("/health", handle_health); // public endpoint (no API key check)
  3934. svr->Get ("/metrics", handle_metrics);
  3935. svr->Get ("/props", handle_props);
  3936. svr->Post("/props", handle_props_change);
  3937. svr->Post("/api/show", handle_api_show);
  3938. svr->Get ("/models", handle_models); // public endpoint (no API key check)
  3939. svr->Get ("/v1/models", handle_models); // public endpoint (no API key check)
  3940. svr->Post("/completion", handle_completions); // legacy
  3941. svr->Post("/completions", handle_completions);
  3942. svr->Post("/v1/completions", handle_completions_oai);
  3943. svr->Post("/chat/completions", handle_chat_completions);
  3944. svr->Post("/v1/chat/completions", handle_chat_completions);
  3945. svr->Post("/infill", handle_infill);
  3946. svr->Post("/embedding", handle_embeddings); // legacy
  3947. svr->Post("/embeddings", handle_embeddings);
  3948. svr->Post("/v1/embeddings", handle_embeddings_oai);
  3949. svr->Post("/rerank", handle_rerank);
  3950. svr->Post("/reranking", handle_rerank);
  3951. svr->Post("/v1/rerank", handle_rerank);
  3952. svr->Post("/v1/reranking", handle_rerank);
  3953. svr->Post("/tokenize", handle_tokenize);
  3954. svr->Post("/detokenize", handle_detokenize);
  3955. svr->Post("/apply-template", handle_apply_template);
  3956. // LoRA adapters hotswap
  3957. svr->Get ("/lora-adapters", handle_lora_adapters_list);
  3958. svr->Post("/lora-adapters", handle_lora_adapters_apply);
  3959. // Save & load slots
  3960. svr->Get ("/slots", handle_slots);
  3961. svr->Post("/slots/:id_slot", handle_slots_action);
  3962. //
  3963. // Start the server
  3964. //
  3965. if (params.n_threads_http < 1) {
  3966. // +2 threads for monitoring endpoints
  3967. params.n_threads_http = std::max(params.n_parallel + 2, (int32_t) std::thread::hardware_concurrency() - 1);
  3968. }
  3969. log_data["n_threads_http"] = std::to_string(params.n_threads_http);
  3970. svr->new_task_queue = [&params] { return new httplib::ThreadPool(params.n_threads_http); };
  3971. // clean up function, to be called before exit
  3972. auto clean_up = [&svr, &ctx_server]() {
  3973. SRV_INF("%s: cleaning up before exit...\n", __func__);
  3974. svr->stop();
  3975. ctx_server.queue_results.terminate();
  3976. llama_backend_free();
  3977. };
  3978. bool was_bound = false;
  3979. if (string_ends_with(std::string(params.hostname), ".sock")) {
  3980. LOG_INF("%s: setting address family to AF_UNIX\n", __func__);
  3981. svr->set_address_family(AF_UNIX);
  3982. // bind_to_port requires a second arg, any value other than 0 should
  3983. // simply get ignored
  3984. was_bound = svr->bind_to_port(params.hostname, 8080);
  3985. } else {
  3986. LOG_INF("%s: binding port with default address family\n", __func__);
  3987. // bind HTTP listen port
  3988. if (params.port == 0) {
  3989. int bound_port = svr->bind_to_any_port(params.hostname);
  3990. if ((was_bound = (bound_port >= 0))) {
  3991. params.port = bound_port;
  3992. }
  3993. } else {
  3994. was_bound = svr->bind_to_port(params.hostname, params.port);
  3995. }
  3996. }
  3997. if (!was_bound) {
  3998. LOG_ERR("%s: couldn't bind HTTP server socket, hostname: %s, port: %d\n", __func__, params.hostname.c_str(), params.port);
  3999. clean_up();
  4000. return 1;
  4001. }
  4002. // run the HTTP server in a thread
  4003. std::thread t([&]() { svr->listen_after_bind(); });
  4004. svr->wait_until_ready();
  4005. LOG_INF("%s: HTTP server is listening, hostname: %s, port: %d, http threads: %d\n", __func__, params.hostname.c_str(), params.port, params.n_threads_http);
  4006. // load the model
  4007. LOG_INF("%s: loading model\n", __func__);
  4008. if (!ctx_server.load_model(params)) {
  4009. clean_up();
  4010. t.join();
  4011. LOG_ERR("%s: exiting due to model loading error\n", __func__);
  4012. return 1;
  4013. }
  4014. ctx_server.init();
  4015. state.store(SERVER_STATE_READY);
  4016. LOG_INF("%s: model loaded\n", __func__);
  4017. // print sample chat example to make it clear which template is used
  4018. LOG_INF("%s: chat template, chat_template: %s, example_format: '%s'\n", __func__,
  4019. common_chat_templates_source(ctx_server.chat_templates.get()),
  4020. common_chat_format_example(ctx_server.chat_templates.get(), ctx_server.params_base.use_jinja).c_str());
  4021. ctx_server.queue_tasks.on_new_task([&ctx_server](server_task && task) {
  4022. ctx_server.process_single_task(std::move(task));
  4023. });
  4024. ctx_server.queue_tasks.on_update_slots([&ctx_server]() {
  4025. ctx_server.update_slots();
  4026. });
  4027. shutdown_handler = [&](int) {
  4028. // this will unblock start_loop()
  4029. ctx_server.queue_tasks.terminate();
  4030. };
  4031. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  4032. struct sigaction sigint_action;
  4033. sigint_action.sa_handler = signal_handler;
  4034. sigemptyset (&sigint_action.sa_mask);
  4035. sigint_action.sa_flags = 0;
  4036. sigaction(SIGINT, &sigint_action, NULL);
  4037. sigaction(SIGTERM, &sigint_action, NULL);
  4038. #elif defined (_WIN32)
  4039. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  4040. return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
  4041. };
  4042. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  4043. #endif
  4044. LOG_INF("%s: server is listening on http://%s:%d - starting the main loop\n", __func__, params.hostname.c_str(), params.port);
  4045. // this call blocks the main thread until queue_tasks.terminate() is called
  4046. ctx_server.queue_tasks.start_loop();
  4047. clean_up();
  4048. t.join();
  4049. return 0;
  4050. }