server.cpp 225 KB

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