server.cpp 218 KB

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