server.cpp 228 KB

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