server.cpp 218 KB

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