server.cpp 196 KB

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