server.cpp 209 KB

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