server.cpp 153 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952
  1. #include "utils.hpp"
  2. #include "arg.h"
  3. #include "common.h"
  4. #include "json-schema-to-grammar.h"
  5. #include "llama.h"
  6. #include "log.h"
  7. #include "sampling.h"
  8. #include "speculative.h"
  9. // Change JSON_ASSERT from assert() to GGML_ASSERT:
  10. #define JSON_ASSERT GGML_ASSERT
  11. #include "json.hpp"
  12. // mime type for sending response
  13. #define MIMETYPE_JSON "application/json; charset=utf-8"
  14. // auto generated files (update with ./deps.sh)
  15. #include "index.html.hpp"
  16. #include "loading.html.hpp"
  17. #include <atomic>
  18. #include <condition_variable>
  19. #include <cstddef>
  20. #include <cinttypes>
  21. #include <deque>
  22. #include <memory>
  23. #include <mutex>
  24. #include <signal.h>
  25. #include <thread>
  26. #include <unordered_map>
  27. #include <unordered_set>
  28. using json = nlohmann::ordered_json;
  29. enum stop_type {
  30. STOP_TYPE_NONE,
  31. STOP_TYPE_EOS,
  32. STOP_TYPE_WORD,
  33. STOP_TYPE_LIMIT,
  34. };
  35. // state diagram: https://github.com/ggerganov/llama.cpp/pull/9283
  36. enum slot_state {
  37. SLOT_STATE_IDLE,
  38. 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
  39. SLOT_STATE_PROCESSING_PROMPT,
  40. SLOT_STATE_DONE_PROMPT,
  41. SLOT_STATE_GENERATING,
  42. };
  43. enum server_state {
  44. SERVER_STATE_LOADING_MODEL, // Server is starting up, model not fully loaded yet
  45. SERVER_STATE_READY, // Server is ready and model is loaded
  46. };
  47. enum server_task_type {
  48. SERVER_TASK_TYPE_INFERENCE,
  49. SERVER_TASK_TYPE_CANCEL,
  50. SERVER_TASK_TYPE_NEXT_RESPONSE,
  51. SERVER_TASK_TYPE_METRICS,
  52. SERVER_TASK_TYPE_SLOT_SAVE,
  53. SERVER_TASK_TYPE_SLOT_RESTORE,
  54. SERVER_TASK_TYPE_SLOT_ERASE,
  55. SERVER_TASK_TYPE_SET_LORA,
  56. };
  57. enum server_task_inf_type {
  58. SERVER_TASK_INF_TYPE_COMPLETION,
  59. SERVER_TASK_INF_TYPE_EMBEDDING,
  60. SERVER_TASK_INF_TYPE_RERANK,
  61. SERVER_TASK_INF_TYPE_INFILL,
  62. };
  63. // https://community.openai.com/t/openai-chat-list-of-error-codes-and-types/357791/11
  64. enum error_type {
  65. ERROR_TYPE_INVALID_REQUEST,
  66. ERROR_TYPE_AUTHENTICATION,
  67. ERROR_TYPE_SERVER,
  68. ERROR_TYPE_NOT_FOUND,
  69. ERROR_TYPE_PERMISSION,
  70. ERROR_TYPE_UNAVAILABLE, // custom error
  71. ERROR_TYPE_NOT_SUPPORTED, // custom error
  72. };
  73. struct server_task {
  74. int id = -1; // to be filled by server_queue
  75. int id_target = -1; // used by SERVER_TASK_TYPE_CANCEL
  76. llama_tokens prompt_tokens;
  77. server_task_type type;
  78. // TODO @ngxson : we should get rid of json type here
  79. json data;
  80. server_task_inf_type inf_type = SERVER_TASK_INF_TYPE_COMPLETION;
  81. // utility function
  82. static std::unordered_set<int> get_list_id(const std::vector<server_task> & tasks) {
  83. std::unordered_set<int> ids(tasks.size());
  84. for (size_t i = 0; i < tasks.size(); i++) {
  85. ids.insert(tasks[i].id);
  86. }
  87. return ids;
  88. }
  89. };
  90. struct slot_params {
  91. bool stream = true;
  92. bool cache_prompt = true; // remember the prompt to avoid reprocessing all prompt
  93. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  94. int32_t n_discard = 0; // number of tokens after n_keep that may be discarded when shifting context, 0 defaults to half
  95. int32_t n_predict = -1; // new tokens to predict
  96. int32_t n_indent = 0; // mininum line indentation for the generated text in number of whitespace characters
  97. int64_t t_max_prompt_ms = -1; // TODO: implement
  98. int64_t t_max_predict_ms = -1; // if positive, limit the generation phase to this time limit
  99. std::vector<std::string> antiprompt;
  100. bool timings_per_token = false;
  101. struct common_params_sampling sampling;
  102. struct common_params_speculative speculative;
  103. // OAI-compat fields
  104. bool verbose = false;
  105. bool oaicompat = false;
  106. bool oaicompat_chat = true;
  107. std::string oaicompat_model;
  108. std::string oaicompat_cmpl_id;
  109. json to_json() const {
  110. std::vector<std::string> samplers;
  111. samplers.reserve(sampling.samplers.size());
  112. for (const auto & sampler : sampling.samplers) {
  113. samplers.emplace_back(common_sampler_type_to_str(sampler));
  114. }
  115. return json {
  116. {"n_predict", n_predict}, // Server configured n_predict
  117. {"seed", sampling.seed},
  118. {"temperature", sampling.temp},
  119. {"dynatemp_range", sampling.dynatemp_range},
  120. {"dynatemp_exponent", sampling.dynatemp_exponent},
  121. {"top_k", sampling.top_k},
  122. {"top_p", sampling.top_p},
  123. {"min_p", sampling.min_p},
  124. {"xtc_probability", sampling.xtc_probability},
  125. {"xtc_threshold", sampling.xtc_threshold},
  126. {"typical_p", sampling.typ_p},
  127. {"repeat_last_n", sampling.penalty_last_n},
  128. {"repeat_penalty", sampling.penalty_repeat},
  129. {"presence_penalty", sampling.penalty_present},
  130. {"frequency_penalty", sampling.penalty_freq},
  131. {"dry_multiplier", sampling.dry_multiplier},
  132. {"dry_base", sampling.dry_base},
  133. {"dry_allowed_length", sampling.dry_allowed_length},
  134. {"dry_penalty_last_n", sampling.dry_penalty_last_n},
  135. {"dry_sequence_breakers", sampling.dry_sequence_breakers},
  136. {"mirostat", sampling.mirostat},
  137. {"mirostat_tau", sampling.mirostat_tau},
  138. {"mirostat_eta", sampling.mirostat_eta},
  139. {"penalize_nl", sampling.penalize_nl},
  140. {"stop", antiprompt},
  141. {"max_tokens", n_predict}, // User configured n_predict
  142. {"n_keep", n_keep},
  143. {"n_discard", n_discard},
  144. {"ignore_eos", sampling.ignore_eos},
  145. {"stream", stream},
  146. //{"logit_bias", sampling.logit_bias},
  147. {"n_probs", sampling.n_probs},
  148. {"min_keep", sampling.min_keep},
  149. {"grammar", sampling.grammar},
  150. {"samplers", samplers},
  151. {"speculative.n_max", speculative.n_max},
  152. {"speculative.n_min", speculative.n_min},
  153. {"speculative.p_min", speculative.p_min},
  154. {"timings_per_token", timings_per_token},
  155. };
  156. }
  157. };
  158. struct result_timings {
  159. int32_t prompt_n = -1;
  160. double prompt_ms;
  161. double prompt_per_token_ms;
  162. double prompt_per_second;
  163. int32_t predicted_n = -1;
  164. double predicted_ms;
  165. double predicted_per_token_ms;
  166. double predicted_per_second;
  167. json to_json() {
  168. return {
  169. {"prompt_n", prompt_n},
  170. {"prompt_ms", prompt_ms},
  171. {"prompt_per_token_ms", prompt_per_token_ms},
  172. {"prompt_per_second", prompt_per_second},
  173. {"predicted_n", predicted_n},
  174. {"predicted_ms", predicted_ms},
  175. {"predicted_per_token_ms", predicted_per_token_ms},
  176. {"predicted_per_second", predicted_per_second},
  177. };
  178. }
  179. };
  180. struct server_task_result {
  181. int id = -1;
  182. int id_slot = -1;
  183. virtual bool is_error() {
  184. // only used by server_task_result_error
  185. return false;
  186. }
  187. virtual bool is_stop() {
  188. // only used by server_task_result_cmpl_partial
  189. return false;
  190. }
  191. virtual int get_index() {
  192. return -1;
  193. }
  194. virtual json to_json() = 0;
  195. virtual ~server_task_result() = default;
  196. };
  197. // using shared_ptr for polymorphism of server_task_result
  198. using server_task_result_ptr = std::unique_ptr<server_task_result>;
  199. inline std::string stop_type_to_str(stop_type type) {
  200. switch (type) {
  201. case STOP_TYPE_EOS: return "eos";
  202. case STOP_TYPE_WORD: return "word";
  203. case STOP_TYPE_LIMIT: return "limit";
  204. default: return "none";
  205. }
  206. }
  207. struct completion_token_output {
  208. llama_token tok;
  209. std::string text_to_send;
  210. struct token_prob {
  211. llama_token tok;
  212. std::string tok_str;
  213. float prob;
  214. };
  215. std::vector<token_prob> probs;
  216. json to_json() const {
  217. json probs_for_token = json::array();
  218. for (const auto & p : probs) {
  219. probs_for_token.push_back(json {
  220. {"tok_str", p.tok_str},
  221. {"prob", p.prob},
  222. });
  223. }
  224. return probs_for_token;
  225. }
  226. static json probs_vector_to_json(const std::vector<completion_token_output> & probs) {
  227. json out = json::array();
  228. for (const auto & prob : probs) {
  229. const std::string tok_str = prob.text_to_send;
  230. out.push_back(json {
  231. {"content", tok_str},
  232. {"probs", prob.to_json()},
  233. });
  234. }
  235. return out;
  236. }
  237. };
  238. struct server_task_result_cmpl_final : server_task_result {
  239. int index = 0;
  240. std::string content;
  241. bool stream;
  242. result_timings timings;
  243. std::string prompt;
  244. bool truncated;
  245. int32_t n_decoded;
  246. int32_t n_prompt_tokens;
  247. int32_t n_tokens_cached;
  248. int32_t has_new_line;
  249. std::string stopping_word;
  250. stop_type stop = STOP_TYPE_NONE;
  251. std::vector<completion_token_output> probs_output;
  252. slot_params generation_params;
  253. // OAI-compat fields
  254. bool verbose = false;
  255. bool oaicompat = false;
  256. bool oaicompat_chat = true; // TODO: support oaicompat for non-chat
  257. std::string oaicompat_model;
  258. std::string oaicompat_cmpl_id;
  259. virtual int get_index() override {
  260. return index;
  261. }
  262. virtual json to_json() override {
  263. return oaicompat ? to_json_oaicompat_chat() : to_json_non_oaicompat();
  264. }
  265. json to_json_non_oaicompat() {
  266. json res = json {
  267. {"index", index},
  268. {"content", content},
  269. {"id_slot", id_slot},
  270. {"stop", true},
  271. {"model", oaicompat_model},
  272. {"tokens_predicted", n_decoded},
  273. {"tokens_evaluated", n_prompt_tokens},
  274. {"generation_settings", generation_params.to_json()},
  275. {"prompt", prompt},
  276. {"has_new_line", has_new_line},
  277. {"truncated", truncated},
  278. {"stop_type", stop_type_to_str(stop)},
  279. {"stopping_word", stopping_word},
  280. {"tokens_cached", n_tokens_cached},
  281. {"timings", timings.to_json()},
  282. };
  283. if (!probs_output.empty()) {
  284. res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output);
  285. }
  286. return res;
  287. }
  288. json to_json_oaicompat_chat() {
  289. std::string finish_reason = "length";
  290. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  291. finish_reason = "stop";
  292. }
  293. json choices = json::array({json{
  294. {"finish_reason", finish_reason},
  295. {"index", 0},
  296. {"message", json{
  297. {"content", content},
  298. {"role", "assistant"}
  299. }
  300. }}});
  301. std::time_t t = std::time(0);
  302. json res = json {
  303. {"choices", choices},
  304. {"created", t},
  305. {"model", oaicompat_model},
  306. {"object", "chat.completion"},
  307. {"usage", json {
  308. {"completion_tokens", n_decoded},
  309. {"prompt_tokens", n_prompt_tokens},
  310. {"total_tokens", n_decoded + n_prompt_tokens}
  311. }},
  312. {"id", oaicompat_cmpl_id}
  313. };
  314. // extra fields for debugging purposes
  315. if (verbose) {
  316. res["__verbose"] = to_json_non_oaicompat();
  317. }
  318. if (timings.prompt_n >= 0) {
  319. res.push_back({"timings", timings.to_json()});
  320. }
  321. return res;
  322. }
  323. };
  324. struct server_task_result_cmpl_partial : server_task_result {
  325. int index = 0;
  326. std::string content;
  327. bool truncated;
  328. int32_t n_decoded;
  329. int32_t n_prompt_tokens;
  330. stop_type stop = STOP_TYPE_NONE;
  331. std::vector<completion_token_output> probs_output;
  332. result_timings timings;
  333. // OAI-compat fields
  334. bool verbose = false;
  335. bool oaicompat = false;
  336. bool oaicompat_chat = true; // TODO: support oaicompat for non-chat
  337. std::string oaicompat_model;
  338. std::string oaicompat_cmpl_id;
  339. virtual int get_index() override {
  340. return index;
  341. }
  342. virtual bool is_stop() override {
  343. return stop != STOP_TYPE_NONE;
  344. }
  345. virtual json to_json() override {
  346. if (oaicompat) {
  347. return to_json_oaicompat();
  348. }
  349. bool is_stop = stop != STOP_TYPE_NONE;
  350. // non-OAI-compat JSON
  351. json res = json {
  352. {"index", index},
  353. {"content", content},
  354. {"stop_type", stop_type_to_str(stop)},
  355. {"stop", is_stop},
  356. {"id_slot", id_slot},
  357. {"tokens_predicted", n_decoded},
  358. {"tokens_evaluated", n_prompt_tokens},
  359. };
  360. // populate the timings object when needed (usually for the last response or with timings_per_token enabled)
  361. if (timings.prompt_n > 0) {
  362. res.push_back({"timings", timings.to_json()});
  363. }
  364. if (!probs_output.empty()) {
  365. res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output);
  366. }
  367. if (is_stop) {
  368. res.push_back({"truncated", truncated});
  369. }
  370. return res;
  371. }
  372. json to_json_oaicompat() {
  373. bool first = n_decoded == 0;
  374. std::string finish_reason;
  375. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  376. finish_reason = "stop";
  377. } else if (stop == STOP_TYPE_LIMIT) {
  378. finish_reason = "length";
  379. }
  380. std::time_t t = std::time(0);
  381. json choices;
  382. if (!finish_reason.empty()) {
  383. choices = json::array({json{{"finish_reason", finish_reason},
  384. {"index", 0},
  385. {"delta", json::object()}}});
  386. } else {
  387. if (first) {
  388. if (content.empty()) {
  389. choices = json::array({json{{"finish_reason", nullptr},
  390. {"index", 0},
  391. {"delta", json{{"role", "assistant"}}}}});
  392. } else {
  393. // We have to send this as two updates to conform to openai behavior
  394. json initial_ret = json{{"choices", json::array({json{
  395. {"finish_reason", nullptr},
  396. {"index", 0},
  397. {"delta", json{
  398. {"role", "assistant"}
  399. }}}})},
  400. {"created", t},
  401. {"id", oaicompat_cmpl_id},
  402. {"model", oaicompat_model},
  403. {"object", "chat.completion.chunk"}};
  404. json second_ret = json{
  405. {"choices", json::array({json{{"finish_reason", nullptr},
  406. {"index", 0},
  407. {"delta", json{
  408. {"content", content}}}
  409. }})},
  410. {"created", t},
  411. {"id", oaicompat_cmpl_id},
  412. {"model", oaicompat_model},
  413. {"object", "chat.completion.chunk"}};
  414. return std::vector<json>({initial_ret, second_ret});
  415. }
  416. } else {
  417. choices = json::array({json{
  418. {"finish_reason", nullptr},
  419. {"index", 0},
  420. {"delta",
  421. json{
  422. {"content", content},
  423. }},
  424. }});
  425. }
  426. }
  427. json ret = json {
  428. {"choices", choices},
  429. {"created", t},
  430. {"id", oaicompat_cmpl_id},
  431. {"model", oaicompat_model},
  432. {"object", "chat.completion.chunk"}
  433. };
  434. if (timings.prompt_n >= 0) {
  435. ret.push_back({"timings", timings.to_json()});
  436. }
  437. if (!finish_reason.empty()) {
  438. ret.push_back({"usage", json {
  439. {"completion_tokens", n_decoded},
  440. {"prompt_tokens", n_prompt_tokens},
  441. {"total_tokens", n_decoded + n_prompt_tokens},
  442. }});
  443. }
  444. return std::vector<json>({ret});
  445. }
  446. };
  447. struct server_task_result_embd : server_task_result {
  448. int index = 0;
  449. std::vector<float> embedding;
  450. virtual int get_index() override {
  451. return index;
  452. }
  453. virtual json to_json() override {
  454. return json {
  455. {"index", index},
  456. {"embedding", embedding},
  457. };
  458. }
  459. };
  460. struct server_task_result_rerank : server_task_result {
  461. int index = 0;
  462. float score = -1e6;
  463. virtual int get_index() override {
  464. return index;
  465. }
  466. virtual json to_json() override {
  467. return json {
  468. {"index", index},
  469. {"score", score},
  470. };
  471. }
  472. };
  473. // this function maybe used outside of server_task_result_error
  474. static json format_error_response(const std::string & message, const enum error_type type) {
  475. std::string type_str;
  476. int code = 500;
  477. switch (type) {
  478. case ERROR_TYPE_INVALID_REQUEST:
  479. type_str = "invalid_request_error";
  480. code = 400;
  481. break;
  482. case ERROR_TYPE_AUTHENTICATION:
  483. type_str = "authentication_error";
  484. code = 401;
  485. break;
  486. case ERROR_TYPE_NOT_FOUND:
  487. type_str = "not_found_error";
  488. code = 404;
  489. break;
  490. case ERROR_TYPE_SERVER:
  491. type_str = "server_error";
  492. code = 500;
  493. break;
  494. case ERROR_TYPE_PERMISSION:
  495. type_str = "permission_error";
  496. code = 403;
  497. break;
  498. case ERROR_TYPE_NOT_SUPPORTED:
  499. type_str = "not_supported_error";
  500. code = 501;
  501. break;
  502. case ERROR_TYPE_UNAVAILABLE:
  503. type_str = "unavailable_error";
  504. code = 503;
  505. break;
  506. }
  507. return json {
  508. {"code", code},
  509. {"message", message},
  510. {"type", type_str},
  511. };
  512. }
  513. struct server_task_result_error : server_task_result {
  514. int index = 0;
  515. error_type err_type = ERROR_TYPE_SERVER;
  516. std::string err_msg;
  517. virtual bool is_error() override {
  518. return true;
  519. }
  520. virtual json to_json() override {
  521. return format_error_response(err_msg, err_type);
  522. }
  523. };
  524. struct server_task_result_metrics : server_task_result {
  525. int n_idle_slots;
  526. int n_processing_slots;
  527. int n_tasks_deferred;
  528. int64_t t_start;
  529. int32_t kv_cache_tokens_count;
  530. int32_t kv_cache_used_cells;
  531. // TODO: somehow reuse server_metrics in the future, instead of duplicating the fields
  532. uint64_t n_prompt_tokens_processed_total = 0;
  533. uint64_t t_prompt_processing_total = 0;
  534. uint64_t n_tokens_predicted_total = 0;
  535. uint64_t t_tokens_generation_total = 0;
  536. uint64_t n_prompt_tokens_processed = 0;
  537. uint64_t t_prompt_processing = 0;
  538. uint64_t n_tokens_predicted = 0;
  539. uint64_t t_tokens_generation = 0;
  540. uint64_t n_decode_total = 0;
  541. uint64_t n_busy_slots_total = 0;
  542. // TODO: get rid of this json object and use to_json() instead
  543. json slots_data = json::array();
  544. virtual json to_json() override {
  545. return json {
  546. { "idle", n_idle_slots },
  547. { "processing", n_processing_slots },
  548. { "deferred", n_tasks_deferred },
  549. { "t_start", t_start },
  550. { "n_prompt_tokens_processed_total", n_prompt_tokens_processed_total },
  551. { "t_tokens_generation_total", t_tokens_generation_total },
  552. { "n_tokens_predicted_total", n_tokens_predicted_total },
  553. { "t_prompt_processing_total", t_prompt_processing_total },
  554. { "n_prompt_tokens_processed", n_prompt_tokens_processed },
  555. { "t_prompt_processing", t_prompt_processing },
  556. { "n_tokens_predicted", n_tokens_predicted },
  557. { "t_tokens_generation", t_tokens_generation },
  558. { "n_decode_total", n_decode_total },
  559. { "n_busy_slots_total", n_busy_slots_total },
  560. { "kv_cache_tokens_count", kv_cache_tokens_count },
  561. { "kv_cache_used_cells", kv_cache_used_cells },
  562. { "slots", slots_data },
  563. };
  564. }
  565. };
  566. struct server_task_result_slot_save_load : server_task_result {
  567. std::string filename;
  568. bool is_save; // true = save, false = load
  569. size_t n_tokens;
  570. size_t n_bytes;
  571. double t_ms;
  572. virtual json to_json() override {
  573. if (is_save) {
  574. return json {
  575. { "id_slot", id_slot },
  576. { "filename", filename },
  577. { "n_saved", n_tokens },
  578. { "n_written", n_bytes },
  579. { "timings", {
  580. { "save_ms", t_ms }
  581. }},
  582. };
  583. } else {
  584. return json {
  585. { "id_slot", id_slot },
  586. { "filename", filename },
  587. { "n_restored", n_tokens },
  588. { "n_read", n_bytes },
  589. { "timings", {
  590. { "restore_ms", t_ms }
  591. }},
  592. };
  593. }
  594. }
  595. };
  596. struct server_task_result_slot_erase : server_task_result {
  597. size_t n_erased;
  598. virtual json to_json() override {
  599. return json {
  600. { "id_slot", id_slot },
  601. { "n_erased", n_erased },
  602. };
  603. }
  604. };
  605. struct server_task_result_apply_lora : server_task_result {
  606. virtual json to_json() override {
  607. return json {{ "success", true }};
  608. }
  609. };
  610. struct server_slot {
  611. int id;
  612. int id_task = -1;
  613. llama_batch batch_spec = {};
  614. llama_context * ctx = nullptr;
  615. llama_context * ctx_dft = nullptr;
  616. common_speculative * spec = nullptr;
  617. // the index relative to completion multi-task request
  618. size_t index = 0;
  619. struct slot_params params;
  620. slot_state state = SLOT_STATE_IDLE;
  621. // used to determine the slot that has been used the longest
  622. int64_t t_last_used = -1;
  623. // generation props
  624. int32_t n_ctx = 0; // context size per slot
  625. int32_t n_past = 0;
  626. int32_t n_decoded = 0;
  627. int32_t n_remaining = -1;
  628. int32_t i_batch = -1;
  629. int32_t n_predict = -1; // TODO: disambiguate from params.n_predict
  630. // n_prompt_tokens may not be equal to prompt_tokens.size(), because prompt maybe truncated
  631. int32_t n_prompt_tokens = 0;
  632. int32_t n_prompt_tokens_processed = 0;
  633. // input prompt tokens
  634. llama_tokens prompt_tokens;
  635. size_t last_nl_pos = 0;
  636. std::string generated_text;
  637. llama_tokens cache_tokens;
  638. std::vector<completion_token_output> generated_token_probs;
  639. server_task_inf_type inf_type = SERVER_TASK_INF_TYPE_COMPLETION;
  640. bool has_next_token = true;
  641. bool has_new_line = false;
  642. bool truncated = false;
  643. stop_type stop;
  644. std::string stopping_word;
  645. // sampling
  646. json json_schema;
  647. struct common_sampler * smpl = nullptr;
  648. llama_token sampled;
  649. // stats
  650. size_t n_sent_text = 0; // number of sent text character
  651. size_t n_sent_token_probs = 0;
  652. int64_t t_start_process_prompt;
  653. int64_t t_start_generation;
  654. double t_prompt_processing; // ms
  655. double t_token_generation; // ms
  656. std::function<void(int)> callback_on_release;
  657. void reset() {
  658. SLT_DBG(*this, "%s", "\n");
  659. n_prompt_tokens = 0;
  660. last_nl_pos = 0;
  661. generated_text = "";
  662. has_new_line = false;
  663. truncated = false;
  664. stop = STOP_TYPE_NONE;
  665. stopping_word = "";
  666. n_past = 0;
  667. n_sent_text = 0;
  668. n_sent_token_probs = 0;
  669. inf_type = SERVER_TASK_INF_TYPE_COMPLETION;
  670. generated_token_probs.clear();
  671. }
  672. bool has_budget(const common_params & global_params) {
  673. if (params.n_predict == -1 && global_params.n_predict == -1) {
  674. return true; // limitless
  675. }
  676. n_remaining = -1;
  677. if (params.n_predict != -1) {
  678. n_remaining = params.n_predict - n_decoded;
  679. } else if (global_params.n_predict != -1) {
  680. n_remaining = global_params.n_predict - n_decoded;
  681. }
  682. return n_remaining > 0; // no budget
  683. }
  684. bool is_processing() const {
  685. return state != SLOT_STATE_IDLE;
  686. }
  687. bool can_speculate() const {
  688. return ctx_dft && params.speculative.n_max > 0 && params.cache_prompt;
  689. }
  690. void add_token(const completion_token_output & token) {
  691. if (!is_processing()) {
  692. SLT_WRN(*this, "%s", "slot is not processing\n");
  693. return;
  694. }
  695. generated_token_probs.push_back(token);
  696. }
  697. void release() {
  698. if (is_processing()) {
  699. SLT_INF(*this, "stop processing: n_past = %d, truncated = %d\n", n_past, truncated);
  700. t_last_used = ggml_time_us();
  701. t_token_generation = (ggml_time_us() - t_start_generation) / 1e3;
  702. state = SLOT_STATE_IDLE;
  703. callback_on_release(id);
  704. }
  705. }
  706. result_timings get_timings() const {
  707. result_timings timings;
  708. timings.prompt_n = n_prompt_tokens_processed;
  709. timings.prompt_ms = t_prompt_processing;
  710. timings.prompt_per_token_ms = t_prompt_processing / n_prompt_tokens_processed;
  711. timings.prompt_per_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  712. timings.predicted_n = n_decoded;
  713. timings.predicted_ms = t_token_generation;
  714. timings.predicted_per_token_ms = t_token_generation / n_decoded;
  715. timings.predicted_per_second = 1e3 / t_token_generation * n_decoded;
  716. return timings;
  717. }
  718. size_t find_stopping_strings(const std::string & text, const size_t last_token_size, bool is_full_stop) {
  719. size_t stop_pos = std::string::npos;
  720. for (const std::string & word : params.antiprompt) {
  721. size_t pos;
  722. if (is_full_stop) {
  723. const size_t tmp = word.size() + last_token_size;
  724. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  725. pos = text.find(word, from_pos);
  726. } else {
  727. // otherwise, partial stop
  728. pos = find_partial_stop_string(word, text);
  729. }
  730. if (pos != std::string::npos && (stop_pos == std::string::npos || pos < stop_pos)) {
  731. if (is_full_stop) {
  732. stop = STOP_TYPE_WORD;
  733. stopping_word = word;
  734. has_next_token = false;
  735. }
  736. stop_pos = pos;
  737. }
  738. }
  739. return stop_pos;
  740. }
  741. void print_timings() const {
  742. const double t_prompt = t_prompt_processing / n_prompt_tokens_processed;
  743. const double n_prompt_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  744. const double t_gen = t_token_generation / n_decoded;
  745. const double n_gen_second = 1e3 / t_token_generation * n_decoded;
  746. SLT_INF(*this,
  747. "\n"
  748. "\rprompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n"
  749. "\r eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n"
  750. "\r total time = %10.2f ms / %5d tokens\n",
  751. t_prompt_processing, n_prompt_tokens_processed, t_prompt, n_prompt_second,
  752. t_token_generation, n_decoded, t_gen, n_gen_second,
  753. t_prompt_processing + t_token_generation, n_prompt_tokens_processed + n_decoded);
  754. }
  755. json to_json() const {
  756. return json {
  757. {"id", id},
  758. {"id_task", id_task},
  759. {"n_ctx", n_ctx},
  760. {"speculative", can_speculate()},
  761. {"is_processing", is_processing()},
  762. {"params", params.to_json()},
  763. {"prompt", common_detokenize(ctx, prompt_tokens)},
  764. {"next_token",
  765. {
  766. {"has_next_token", has_next_token},
  767. {"has_new_line", has_new_line},
  768. {"n_remain", n_remaining},
  769. {"n_decoded", n_decoded},
  770. {"stopping_word", stopping_word},
  771. }
  772. },
  773. };
  774. }
  775. };
  776. struct server_metrics {
  777. int64_t t_start = 0;
  778. uint64_t n_prompt_tokens_processed_total = 0;
  779. uint64_t t_prompt_processing_total = 0;
  780. uint64_t n_tokens_predicted_total = 0;
  781. uint64_t t_tokens_generation_total = 0;
  782. uint64_t n_prompt_tokens_processed = 0;
  783. uint64_t t_prompt_processing = 0;
  784. uint64_t n_tokens_predicted = 0;
  785. uint64_t t_tokens_generation = 0;
  786. uint64_t n_decode_total = 0;
  787. uint64_t n_busy_slots_total = 0;
  788. void init() {
  789. t_start = ggml_time_us();
  790. }
  791. void on_prompt_eval(const server_slot & slot) {
  792. n_prompt_tokens_processed_total += slot.n_prompt_tokens_processed;
  793. n_prompt_tokens_processed += slot.n_prompt_tokens_processed;
  794. t_prompt_processing += slot.t_prompt_processing;
  795. t_prompt_processing_total += slot.t_prompt_processing;
  796. }
  797. void on_prediction(const server_slot & slot) {
  798. n_tokens_predicted_total += slot.n_decoded;
  799. n_tokens_predicted += slot.n_decoded;
  800. t_tokens_generation += slot.t_token_generation;
  801. t_tokens_generation_total += slot.t_token_generation;
  802. }
  803. void on_decoded(const std::vector<server_slot> & slots) {
  804. n_decode_total++;
  805. for (const auto & slot : slots) {
  806. if (slot.is_processing()) {
  807. n_busy_slots_total++;
  808. }
  809. }
  810. }
  811. void reset_bucket() {
  812. n_prompt_tokens_processed = 0;
  813. t_prompt_processing = 0;
  814. n_tokens_predicted = 0;
  815. t_tokens_generation = 0;
  816. }
  817. };
  818. struct server_queue {
  819. int id = 0;
  820. bool running;
  821. // queues
  822. std::deque<server_task> queue_tasks;
  823. std::deque<server_task> queue_tasks_deferred;
  824. std::mutex mutex_tasks;
  825. std::condition_variable condition_tasks;
  826. // callback functions
  827. std::function<void(server_task)> callback_new_task;
  828. std::function<void(void)> callback_update_slots;
  829. // Add a new task to the end of the queue
  830. int post(server_task task, bool front = false) {
  831. std::unique_lock<std::mutex> lock(mutex_tasks);
  832. if (task.id == -1) {
  833. task.id = id++;
  834. }
  835. QUE_DBG("new task, id = %d, front = %d\n", task.id, front);
  836. if (front) {
  837. queue_tasks.push_front(std::move(task));
  838. } else {
  839. queue_tasks.push_back(std::move(task));
  840. }
  841. condition_tasks.notify_one();
  842. return task.id;
  843. }
  844. // multi-task version of post()
  845. int post(std::vector<server_task> & tasks, bool front = false) {
  846. std::unique_lock<std::mutex> lock(mutex_tasks);
  847. for (auto & task : tasks) {
  848. if (task.id == -1) {
  849. task.id = id++;
  850. }
  851. QUE_DBG("new task, id = %d/%d, front = %d\n", task.id, (int) tasks.size(), front);
  852. if (front) {
  853. queue_tasks.push_front(std::move(task));
  854. } else {
  855. queue_tasks.push_back(std::move(task));
  856. }
  857. }
  858. condition_tasks.notify_one();
  859. return 0;
  860. }
  861. // Add a new task, but defer until one slot is available
  862. void defer(server_task task) {
  863. std::unique_lock<std::mutex> lock(mutex_tasks);
  864. QUE_DBG("defer task, id = %d\n", task.id);
  865. queue_tasks_deferred.push_back(std::move(task));
  866. condition_tasks.notify_one();
  867. }
  868. // Get the next id for creating a new task
  869. int get_new_id() {
  870. std::unique_lock<std::mutex> lock(mutex_tasks);
  871. int new_id = id++;
  872. return new_id;
  873. }
  874. // Register function to process a new task
  875. void on_new_task(std::function<void(server_task)> callback) {
  876. callback_new_task = std::move(callback);
  877. }
  878. // Register the function to be called when all slots data is ready to be processed
  879. void on_update_slots(std::function<void(void)> callback) {
  880. callback_update_slots = std::move(callback);
  881. }
  882. // Call when the state of one slot is changed, it will move one task from deferred to main queue
  883. void pop_deferred_task() {
  884. std::unique_lock<std::mutex> lock(mutex_tasks);
  885. if (!queue_tasks_deferred.empty()) {
  886. queue_tasks.emplace_back(std::move(queue_tasks_deferred.front()));
  887. queue_tasks_deferred.pop_front();
  888. }
  889. condition_tasks.notify_one();
  890. }
  891. // end the start_loop routine
  892. void terminate() {
  893. std::unique_lock<std::mutex> lock(mutex_tasks);
  894. running = false;
  895. condition_tasks.notify_all();
  896. }
  897. /**
  898. * Main loop consists of these steps:
  899. * - Wait until a new task arrives
  900. * - Process the task (i.e. maybe copy data into slot)
  901. * - Check if multitask is finished
  902. * - Update all slots
  903. */
  904. void start_loop() {
  905. running = true;
  906. while (true) {
  907. QUE_DBG("%s", "processing new tasks\n");
  908. while (true) {
  909. std::unique_lock<std::mutex> lock(mutex_tasks);
  910. if (queue_tasks.empty()) {
  911. lock.unlock();
  912. break;
  913. }
  914. server_task task = queue_tasks.front();
  915. queue_tasks.pop_front();
  916. lock.unlock();
  917. QUE_DBG("processing task, id = %d\n", task.id);
  918. callback_new_task(std::move(task));
  919. }
  920. // all tasks in the current loop is processed, slots data is now ready
  921. QUE_DBG("%s", "update slots\n");
  922. callback_update_slots();
  923. QUE_DBG("%s", "waiting for new tasks\n");
  924. {
  925. std::unique_lock<std::mutex> lock(mutex_tasks);
  926. if (queue_tasks.empty()) {
  927. if (!running) {
  928. QUE_DBG("%s", "terminate\n");
  929. return;
  930. }
  931. condition_tasks.wait(lock, [&]{
  932. return (!queue_tasks.empty() || !running);
  933. });
  934. }
  935. }
  936. }
  937. }
  938. };
  939. struct server_response {
  940. // for keeping track of all tasks waiting for the result
  941. std::unordered_set<int> waiting_task_ids;
  942. // the main result queue (using ptr for polymorphism)
  943. std::vector<server_task_result_ptr> queue_results;
  944. std::mutex mutex_results;
  945. std::condition_variable condition_results;
  946. // add the id_task to the list of tasks waiting for response
  947. void add_waiting_task_id(int id_task) {
  948. SRV_DBG("add task %d to waiting list. current waiting = %d (before add)\n", id_task, (int) waiting_task_ids.size());
  949. std::unique_lock<std::mutex> lock(mutex_results);
  950. waiting_task_ids.insert(id_task);
  951. }
  952. void add_waiting_tasks(const std::vector<server_task> & tasks) {
  953. std::unique_lock<std::mutex> lock(mutex_results);
  954. for (const auto & task : tasks) {
  955. SRV_DBG("add task %d to waiting list. current waiting = %d (before add)\n", task.id, (int) waiting_task_ids.size());
  956. waiting_task_ids.insert(task.id);
  957. }
  958. }
  959. // when the request is finished, we can remove task associated with it
  960. void remove_waiting_task_id(int id_task) {
  961. SRV_DBG("remove task %d from waiting list. current waiting = %d (before remove)\n", id_task, (int) waiting_task_ids.size());
  962. std::unique_lock<std::mutex> lock(mutex_results);
  963. waiting_task_ids.erase(id_task);
  964. }
  965. void remove_waiting_task_ids(const std::unordered_set<int> & id_tasks) {
  966. std::unique_lock<std::mutex> lock(mutex_results);
  967. for (const auto & id_task : id_tasks) {
  968. SRV_DBG("remove task %d from waiting list. current waiting = %d (before remove)\n", id_task, (int) waiting_task_ids.size());
  969. waiting_task_ids.erase(id_task);
  970. }
  971. }
  972. // This function blocks the thread until there is a response for one of the id_tasks
  973. server_task_result_ptr recv(const std::unordered_set<int> & id_tasks) {
  974. while (true) {
  975. std::unique_lock<std::mutex> lock(mutex_results);
  976. condition_results.wait(lock, [&]{
  977. return !queue_results.empty();
  978. });
  979. for (int i = 0; i < (int) queue_results.size(); i++) {
  980. if (id_tasks.find(queue_results[i]->id) != id_tasks.end()) {
  981. server_task_result_ptr res = std::move(queue_results[i]);
  982. queue_results.erase(queue_results.begin() + i);
  983. return res;
  984. }
  985. }
  986. }
  987. // should never reach here
  988. }
  989. // single-task version of recv()
  990. server_task_result_ptr recv(int id_task) {
  991. std::unordered_set<int> id_tasks = {id_task};
  992. return recv(id_tasks);
  993. }
  994. // Send a new result to a waiting id_task
  995. void send(server_task_result_ptr && result) {
  996. SRV_DBG("sending result for task id = %d\n", result->id);
  997. std::unique_lock<std::mutex> lock(mutex_results);
  998. for (const auto & id_task : waiting_task_ids) {
  999. if (result->id == id_task) {
  1000. SRV_DBG("task id = %d pushed to result queue\n", result->id);
  1001. queue_results.emplace_back(std::move(result));
  1002. condition_results.notify_all();
  1003. return;
  1004. }
  1005. }
  1006. }
  1007. };
  1008. struct server_context {
  1009. common_params params_base;
  1010. llama_model * model = nullptr;
  1011. llama_context * ctx = nullptr;
  1012. std::vector<common_lora_adapter_container> loras;
  1013. llama_model * model_dft = nullptr;
  1014. llama_context_params cparams_dft;
  1015. llama_batch batch = {};
  1016. bool clean_kv_cache = true;
  1017. bool add_bos_token = true;
  1018. bool has_eos_token = false;
  1019. int32_t n_ctx; // total context for all clients / slots
  1020. // slots / clients
  1021. std::vector<server_slot> slots;
  1022. json default_generation_settings_for_props;
  1023. server_queue queue_tasks;
  1024. server_response queue_results;
  1025. server_metrics metrics;
  1026. // Necessary similarity of prompt for slot selection
  1027. float slot_prompt_similarity = 0.0f;
  1028. ~server_context() {
  1029. if (ctx) {
  1030. llama_free(ctx);
  1031. ctx = nullptr;
  1032. }
  1033. if (model) {
  1034. llama_free_model(model);
  1035. model = nullptr;
  1036. }
  1037. if (model_dft) {
  1038. llama_free_model(model_dft);
  1039. model_dft = nullptr;
  1040. }
  1041. // Clear any sampling context
  1042. for (server_slot & slot : slots) {
  1043. common_sampler_free(slot.smpl);
  1044. slot.smpl = nullptr;
  1045. llama_free(slot.ctx_dft);
  1046. slot.ctx_dft = nullptr;
  1047. common_speculative_free(slot.spec);
  1048. slot.spec = nullptr;
  1049. llama_batch_free(slot.batch_spec);
  1050. }
  1051. llama_batch_free(batch);
  1052. }
  1053. bool load_model(const common_params & params) {
  1054. SRV_INF("loading model '%s'\n", params.model.c_str());
  1055. params_base = params;
  1056. common_init_result llama_init = common_init_from_params(params_base);
  1057. model = llama_init.model;
  1058. ctx = llama_init.context;
  1059. loras = llama_init.lora_adapters;
  1060. if (model == nullptr) {
  1061. SRV_ERR("failed to load model, '%s'\n", params_base.model.c_str());
  1062. return false;
  1063. }
  1064. n_ctx = llama_n_ctx(ctx);
  1065. add_bos_token = llama_add_bos_token(model);
  1066. has_eos_token = !llama_add_eos_token(model);
  1067. if (!params_base.speculative.model.empty()) {
  1068. SRV_INF("loading draft model '%s'\n", params_base.speculative.model.c_str());
  1069. auto params_dft = params_base;
  1070. params_dft.devices = params_base.speculative.devices;
  1071. params_dft.model = params_base.speculative.model;
  1072. params_dft.n_ctx = params_base.speculative.n_ctx == 0 ? params_base.n_ctx / params_base.n_parallel : params_base.speculative.n_ctx;
  1073. params_dft.n_gpu_layers = params_base.speculative.n_gpu_layers;
  1074. params_dft.n_parallel = 1;
  1075. common_init_result llama_init_dft = common_init_from_params(params_dft);
  1076. model_dft = llama_init_dft.model;
  1077. if (model_dft == nullptr) {
  1078. SRV_ERR("failed to load draft model, '%s'\n", params_base.speculative.model.c_str());
  1079. return false;
  1080. }
  1081. if (!common_speculative_are_compatible(ctx, llama_init_dft.context)) {
  1082. SRV_ERR("the draft model '%s' is not compatible with the target model '%s'\n", params_base.speculative.model.c_str(), params_base.model.c_str());
  1083. llama_free (llama_init_dft.context);
  1084. llama_free_model(llama_init_dft.model);
  1085. return false;
  1086. }
  1087. const int n_ctx_dft = llama_n_ctx(llama_init_dft.context);
  1088. cparams_dft = common_context_params_to_llama(params_dft);
  1089. cparams_dft.n_batch = n_ctx_dft;
  1090. // force F16 KV cache for the draft model for extra performance
  1091. cparams_dft.type_k = GGML_TYPE_F16;
  1092. cparams_dft.type_v = GGML_TYPE_F16;
  1093. // the context is not needed - we will create one for each slot
  1094. llama_free(llama_init_dft.context);
  1095. }
  1096. return true;
  1097. }
  1098. bool validate_model_chat_template() const {
  1099. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  1100. std::string template_key = "tokenizer.chat_template";
  1101. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  1102. if (res >= 0) {
  1103. llama_chat_message chat[] = {{"user", "test"}};
  1104. std::string tmpl = std::string(model_template.data(), model_template.size());
  1105. int32_t chat_res = llama_chat_apply_template(model, tmpl.c_str(), chat, 1, true, nullptr, 0);
  1106. return chat_res > 0;
  1107. }
  1108. return false;
  1109. }
  1110. void init() {
  1111. const int32_t n_ctx_slot = n_ctx / params_base.n_parallel;
  1112. SRV_INF("initializing slots, n_slots = %d\n", params_base.n_parallel);
  1113. for (int i = 0; i < params_base.n_parallel; i++) {
  1114. server_slot slot;
  1115. slot.id = i;
  1116. slot.ctx = ctx;
  1117. slot.n_ctx = n_ctx_slot;
  1118. slot.n_predict = params_base.n_predict;
  1119. if (model_dft) {
  1120. slot.batch_spec = llama_batch_init(params_base.speculative.n_max + 1, 0, 1);
  1121. slot.ctx_dft = llama_new_context_with_model(model_dft, cparams_dft);
  1122. if (slot.ctx_dft == nullptr) {
  1123. SRV_ERR("%s", "failed to create draft context\n");
  1124. return;
  1125. }
  1126. slot.spec = common_speculative_init(slot.ctx_dft);
  1127. if (slot.spec == nullptr) {
  1128. SRV_ERR("%s", "failed to create speculator\n");
  1129. return;
  1130. }
  1131. }
  1132. SLT_INF(slot, "new slot n_ctx_slot = %d\n", slot.n_ctx);
  1133. slot.params.sampling = params_base.sampling;
  1134. slot.callback_on_release = [this](int) {
  1135. queue_tasks.pop_deferred_task();
  1136. };
  1137. slot.reset();
  1138. slots.push_back(slot);
  1139. }
  1140. default_generation_settings_for_props = slots[0].to_json();
  1141. // the update_slots() logic will always submit a maximum of n_batch or n_parallel tokens
  1142. // 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)
  1143. {
  1144. const int32_t n_batch = llama_n_batch(ctx);
  1145. // only a single seq_id per token is needed
  1146. batch = llama_batch_init(std::max(n_batch, params_base.n_parallel), 0, 1);
  1147. }
  1148. metrics.init();
  1149. }
  1150. server_slot * get_slot_by_id(int id) {
  1151. for (server_slot & slot : slots) {
  1152. if (slot.id == id) {
  1153. return &slot;
  1154. }
  1155. }
  1156. return nullptr;
  1157. }
  1158. server_slot * get_available_slot(const server_task & task) {
  1159. server_slot * ret = nullptr;
  1160. // find the slot that has at least n% prompt similarity
  1161. if (ret == nullptr && slot_prompt_similarity != 0.0f) {
  1162. int lcs_len = 0;
  1163. float similarity = 0;
  1164. for (server_slot & slot : slots) {
  1165. // skip the slot if it is not available
  1166. if (slot.is_processing()) {
  1167. continue;
  1168. }
  1169. // skip the slot if it does not contains cached tokens
  1170. if (slot.cache_tokens.empty()) {
  1171. continue;
  1172. }
  1173. // length of the Longest Common Subsequence between the current slot's prompt and the input prompt
  1174. int cur_lcs_len = common_lcs(slot.cache_tokens, task.prompt_tokens);
  1175. // fraction of the common subsequence length compared to the current slot's prompt length
  1176. float cur_similarity = static_cast<float>(cur_lcs_len) / static_cast<int>(slot.cache_tokens.size());
  1177. // select the current slot if the criteria match
  1178. if (cur_lcs_len > lcs_len && cur_similarity > slot_prompt_similarity) {
  1179. lcs_len = cur_lcs_len;
  1180. similarity = cur_similarity;
  1181. ret = &slot;
  1182. }
  1183. }
  1184. if (ret != nullptr) {
  1185. SLT_DBG(*ret, "selected slot by lcs similarity, lcs_len = %d, similarity = %f\n", lcs_len, similarity);
  1186. }
  1187. }
  1188. // find the slot that has been least recently used
  1189. if (ret == nullptr) {
  1190. int64_t t_last = ggml_time_us();
  1191. for (server_slot & slot : slots) {
  1192. // skip the slot if it is not available
  1193. if (slot.is_processing()) {
  1194. continue;
  1195. }
  1196. // select the current slot if the criteria match
  1197. if (slot.t_last_used < t_last) {
  1198. t_last = slot.t_last_used;
  1199. ret = &slot;
  1200. }
  1201. }
  1202. if (ret != nullptr) {
  1203. SLT_DBG(*ret, "selected slot by lru, t_last = %" PRId64 "\n", t_last);
  1204. }
  1205. }
  1206. return ret;
  1207. }
  1208. bool launch_slot_with_task(server_slot & slot, const server_task & task) {
  1209. // Sampling parameter defaults are loaded from the global server context (but individual requests can still override them)
  1210. slot_params defaults;
  1211. defaults.sampling = params_base.sampling;
  1212. defaults.speculative = params_base.speculative;
  1213. const auto & data = task.data;
  1214. if (data.count("__oaicompat") != 0) {
  1215. std::string model_name = params_base.model_alias.empty() ? DEFAULT_OAICOMPAT_MODEL : params_base.model_alias;
  1216. slot.params.oaicompat = true;
  1217. slot.params.oaicompat_chat = json_value(data, "__oaicompat_chat", false);
  1218. slot.params.oaicompat_model = json_value(data, "model", model_name);
  1219. slot.params.oaicompat_cmpl_id = json_value(data, "completion_id", std::string());
  1220. } else {
  1221. slot.params.oaicompat = false;
  1222. }
  1223. // enabling this will output extra debug information in the HTTP responses from the server
  1224. slot.params.verbose = params_base.verbosity > 9;
  1225. slot.params.timings_per_token = json_value(data, "timings_per_token", false);
  1226. slot.params.stream = json_value(data, "stream", false);
  1227. slot.params.cache_prompt = json_value(data, "cache_prompt", true);
  1228. slot.params.n_predict = json_value(data, "n_predict", json_value(data, "max_tokens", defaults.n_predict));
  1229. slot.params.n_indent = json_value(data, "n_indent", defaults.n_indent);
  1230. slot.params.n_keep = json_value(data, "n_keep", defaults.n_keep);
  1231. slot.params.n_discard = json_value(data, "n_discard", defaults.n_discard);
  1232. //slot.params.t_max_prompt_ms = json_value(data, "t_max_prompt_ms", defaults.t_max_prompt_ms); // TODO: implement
  1233. slot.params.t_max_predict_ms = json_value(data, "t_max_predict_ms", defaults.t_max_predict_ms);
  1234. slot.params.sampling.top_k = json_value(data, "top_k", defaults.sampling.top_k);
  1235. slot.params.sampling.top_p = json_value(data, "top_p", defaults.sampling.top_p);
  1236. slot.params.sampling.min_p = json_value(data, "min_p", defaults.sampling.min_p);
  1237. slot.params.sampling.xtc_probability = json_value(data, "xtc_probability", defaults.sampling.xtc_probability);
  1238. slot.params.sampling.xtc_threshold = json_value(data, "xtc_threshold", defaults.sampling.xtc_threshold);
  1239. slot.params.sampling.typ_p = json_value(data, "typical_p", defaults.sampling.typ_p);
  1240. slot.params.sampling.temp = json_value(data, "temperature", defaults.sampling.temp);
  1241. slot.params.sampling.dynatemp_range = json_value(data, "dynatemp_range", defaults.sampling.dynatemp_range);
  1242. slot.params.sampling.dynatemp_exponent = json_value(data, "dynatemp_exponent", defaults.sampling.dynatemp_exponent);
  1243. slot.params.sampling.penalty_last_n = json_value(data, "repeat_last_n", defaults.sampling.penalty_last_n);
  1244. slot.params.sampling.penalty_repeat = json_value(data, "repeat_penalty", defaults.sampling.penalty_repeat);
  1245. slot.params.sampling.penalty_freq = json_value(data, "frequency_penalty", defaults.sampling.penalty_freq);
  1246. slot.params.sampling.penalty_present = json_value(data, "presence_penalty", defaults.sampling.penalty_present);
  1247. slot.params.sampling.dry_multiplier = json_value(data, "dry_multiplier", defaults.sampling.dry_multiplier);
  1248. slot.params.sampling.dry_base = json_value(data, "dry_base", defaults.sampling.dry_base);
  1249. slot.params.sampling.dry_allowed_length = json_value(data, "dry_allowed_length", defaults.sampling.dry_allowed_length);
  1250. slot.params.sampling.dry_penalty_last_n = json_value(data, "dry_penalty_last_n", defaults.sampling.dry_penalty_last_n);
  1251. slot.params.sampling.mirostat = json_value(data, "mirostat", defaults.sampling.mirostat);
  1252. slot.params.sampling.mirostat_tau = json_value(data, "mirostat_tau", defaults.sampling.mirostat_tau);
  1253. slot.params.sampling.mirostat_eta = json_value(data, "mirostat_eta", defaults.sampling.mirostat_eta);
  1254. slot.params.sampling.penalize_nl = json_value(data, "penalize_nl", defaults.sampling.penalize_nl);
  1255. slot.params.sampling.seed = json_value(data, "seed", defaults.sampling.seed);
  1256. slot.params.sampling.n_probs = json_value(data, "n_probs", defaults.sampling.n_probs);
  1257. slot.params.sampling.min_keep = json_value(data, "min_keep", defaults.sampling.min_keep);
  1258. slot.params.speculative.n_min = json_value(data, "speculative.n_min", defaults.speculative.n_min);
  1259. slot.params.speculative.n_max = json_value(data, "speculative.n_max", defaults.speculative.n_max);
  1260. slot.params.speculative.p_min = json_value(data, "speculative.p_min", defaults.speculative.p_min);
  1261. slot.params.speculative.n_min = std::min(slot.params.speculative.n_max, slot.params.speculative.n_min);
  1262. slot.params.speculative.n_min = std::max(slot.params.speculative.n_min, 2);
  1263. slot.params.speculative.n_max = std::max(slot.params.speculative.n_max, 0);
  1264. if (slot.params.sampling.dry_base < 1.0f) {
  1265. slot.params.sampling.dry_base = defaults.sampling.dry_base;
  1266. }
  1267. // sequence breakers for DRY
  1268. {
  1269. // Currently, this is not compatible with TextGen WebUI, Koboldcpp and SillyTavern format
  1270. // Ref: https://github.com/oobabooga/text-generation-webui/blob/d1af7a41ade7bd3c3a463bfa640725edb818ebaf/extensions/openai/typing.py#L39
  1271. if (data.contains("dry_sequence_breakers")) {
  1272. slot.params.sampling.dry_sequence_breakers = json_value(data, "dry_sequence_breakers", std::vector<std::string>());
  1273. if (slot.params.sampling.dry_sequence_breakers.empty()) {
  1274. send_error(task, "Error: dry_sequence_breakers must be a non-empty array of strings", ERROR_TYPE_INVALID_REQUEST);
  1275. return false;
  1276. }
  1277. }
  1278. }
  1279. // process "json_schema" and "grammar"
  1280. if (data.contains("json_schema") && !data.at("json_schema").is_null() && data.contains("grammar") && !data.at("grammar").is_null()) {
  1281. send_error(task, "Either \"json_schema\" or \"grammar\" can be specified, but not both", ERROR_TYPE_INVALID_REQUEST);
  1282. return false;
  1283. }
  1284. if (data.contains("json_schema") && !data.contains("grammar")) {
  1285. try {
  1286. auto schema = json_value(data, "json_schema", json::object());
  1287. slot.params.sampling.grammar = json_schema_to_grammar(schema);
  1288. } catch (const std::exception & e) {
  1289. send_error(task, std::string("\"json_schema\": ") + e.what(), ERROR_TYPE_INVALID_REQUEST);
  1290. return false;
  1291. }
  1292. } else {
  1293. slot.params.sampling.grammar = json_value(data, "grammar", defaults.sampling.grammar);
  1294. }
  1295. if (slot.n_predict > 0 && slot.params.n_predict > slot.n_predict) {
  1296. // Might be better to reject the request with a 400 ?
  1297. slot.params.n_predict = slot.n_predict;
  1298. SLT_WRN(slot, "n_predict = %d exceeds server configuration, setting to %d", slot.n_predict, slot.n_predict);
  1299. }
  1300. {
  1301. slot.params.sampling.logit_bias.clear();
  1302. if (json_value(data, "ignore_eos", false) && has_eos_token) {
  1303. slot.params.sampling.logit_bias.push_back({llama_token_eos(model), -INFINITY});
  1304. }
  1305. const auto & logit_bias = data.find("logit_bias");
  1306. if (logit_bias != data.end() && logit_bias->is_array()) {
  1307. const int n_vocab = llama_n_vocab(model);
  1308. for (const auto & el : *logit_bias) {
  1309. // TODO: we may want to throw errors here, in case "el" is incorrect
  1310. if (el.is_array() && el.size() == 2) {
  1311. float bias;
  1312. if (el[1].is_number()) {
  1313. bias = el[1].get<float>();
  1314. } else if (el[1].is_boolean() && !el[1].get<bool>()) {
  1315. bias = -INFINITY;
  1316. } else {
  1317. continue;
  1318. }
  1319. if (el[0].is_number_integer()) {
  1320. llama_token tok = el[0].get<llama_token>();
  1321. if (tok >= 0 && tok < n_vocab) {
  1322. slot.params.sampling.logit_bias.push_back({tok, bias});
  1323. }
  1324. } else if (el[0].is_string()) {
  1325. auto toks = common_tokenize(model, el[0].get<std::string>(), false);
  1326. for (auto tok : toks) {
  1327. slot.params.sampling.logit_bias.push_back({tok, bias});
  1328. }
  1329. }
  1330. }
  1331. }
  1332. }
  1333. }
  1334. {
  1335. slot.params.antiprompt.clear();
  1336. const auto & stop = data.find("stop");
  1337. if (stop != data.end() && stop->is_array()) {
  1338. for (const auto & word : *stop) {
  1339. if (!word.empty()) {
  1340. slot.params.antiprompt.push_back(word);
  1341. }
  1342. }
  1343. }
  1344. }
  1345. {
  1346. const auto & samplers = data.find("samplers");
  1347. if (samplers != data.end()) {
  1348. if (samplers->is_array()) {
  1349. std::vector<std::string> sampler_names;
  1350. for (const auto & name : *samplers) {
  1351. if (name.is_string()) {
  1352. sampler_names.emplace_back(name);
  1353. }
  1354. }
  1355. slot.params.sampling.samplers = common_sampler_types_from_names(sampler_names, false);
  1356. } else if (samplers->is_string()){
  1357. std::string sampler_string;
  1358. for (const auto & name : *samplers) {
  1359. sampler_string += name;
  1360. }
  1361. slot.params.sampling.samplers = common_sampler_types_from_chars(sampler_string);
  1362. }
  1363. } else {
  1364. slot.params.sampling.samplers = defaults.sampling.samplers;
  1365. }
  1366. }
  1367. {
  1368. if (slot.smpl != nullptr) {
  1369. common_sampler_free(slot.smpl);
  1370. }
  1371. slot.smpl = common_sampler_init(model, slot.params.sampling);
  1372. if (slot.smpl == nullptr) {
  1373. // for now, the only error that may happen here is invalid grammar
  1374. send_error(task, "Failed to parse grammar", ERROR_TYPE_INVALID_REQUEST);
  1375. return false;
  1376. }
  1377. }
  1378. if (slot.ctx_dft) {
  1379. llama_batch_free(slot.batch_spec);
  1380. slot.batch_spec = llama_batch_init(slot.params.speculative.n_max + 1, 0, 1);
  1381. }
  1382. slot.state = SLOT_STATE_STARTED;
  1383. SLT_INF(slot, "%s", "processing task\n");
  1384. return true;
  1385. }
  1386. void kv_cache_clear() {
  1387. SRV_DBG("%s", "clearing KV cache\n");
  1388. // clear the entire KV cache
  1389. llama_kv_cache_clear(ctx);
  1390. clean_kv_cache = false;
  1391. }
  1392. bool process_token(completion_token_output & result, server_slot & slot) {
  1393. // remember which tokens were sampled - used for repetition penalties during sampling
  1394. const std::string token_str = common_token_to_piece(ctx, result.tok, params_base.special);
  1395. slot.sampled = result.tok;
  1396. // search stop word and delete it
  1397. slot.generated_text += token_str;
  1398. slot.has_next_token = true;
  1399. // check if there is incomplete UTF-8 character at the end
  1400. bool incomplete = false;
  1401. for (unsigned i = 1; i < 5 && i <= slot.generated_text.size(); ++i) {
  1402. unsigned char c = slot.generated_text[slot.generated_text.size() - i];
  1403. if ((c & 0xC0) == 0x80) {
  1404. // continuation byte: 10xxxxxx
  1405. continue;
  1406. }
  1407. if ((c & 0xE0) == 0xC0) {
  1408. // 2-byte character: 110xxxxx ...
  1409. incomplete = i < 2;
  1410. } else if ((c & 0xF0) == 0xE0) {
  1411. // 3-byte character: 1110xxxx ...
  1412. incomplete = i < 3;
  1413. } else if ((c & 0xF8) == 0xF0) {
  1414. // 4-byte character: 11110xxx ...
  1415. incomplete = i < 4;
  1416. }
  1417. // else 1-byte character or invalid byte
  1418. break;
  1419. }
  1420. if (!incomplete) {
  1421. size_t pos = std::min(slot.n_sent_text, slot.generated_text.size());
  1422. const std::string str_test = slot.generated_text.substr(pos);
  1423. bool send_text = true;
  1424. size_t stop_pos = slot.find_stopping_strings(str_test, token_str.size(), true);
  1425. if (stop_pos != std::string::npos) {
  1426. slot.generated_text.erase(
  1427. slot.generated_text.begin() + pos + stop_pos,
  1428. slot.generated_text.end());
  1429. pos = std::min(slot.n_sent_text, slot.generated_text.size());
  1430. } else if (slot.has_next_token) {
  1431. stop_pos = slot.find_stopping_strings(str_test, token_str.size(), false);
  1432. send_text = stop_pos == std::string::npos;
  1433. }
  1434. // check if there is any token to predict
  1435. if (send_text) {
  1436. // no send the stop word in the response
  1437. result.text_to_send = slot.generated_text.substr(pos, std::string::npos);
  1438. slot.n_sent_text += result.text_to_send.size();
  1439. // add the token to slot queue and cache
  1440. }
  1441. slot.add_token(result);
  1442. if (slot.params.stream) {
  1443. send_partial_response(slot, result);
  1444. }
  1445. }
  1446. if (incomplete) {
  1447. slot.has_next_token = true;
  1448. }
  1449. // check the limits
  1450. if (slot.n_decoded > 0 && slot.has_next_token && !slot.has_budget(params_base)) {
  1451. slot.stop = STOP_TYPE_LIMIT;
  1452. slot.has_next_token = false;
  1453. SLT_DBG(slot, "stopped by limit, n_decoded = %d, n_predict = %d\n", slot.n_decoded, slot.params.n_predict);
  1454. }
  1455. if (slot.has_new_line) {
  1456. // if we have already seen a new line, we stop after a certain time limit
  1457. if (slot.params.t_max_predict_ms > 0 && (ggml_time_us() - slot.t_start_generation > 1000.0f*slot.params.t_max_predict_ms)) {
  1458. slot.stop = STOP_TYPE_LIMIT;
  1459. slot.has_next_token = false;
  1460. 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);
  1461. }
  1462. // require that each new line has a whitespace prefix (i.e. indentation) of at least slot.params.n_indent
  1463. if (slot.params.n_indent > 0) {
  1464. // check the current indentation
  1465. // TODO: improve by not doing it more than once for each new line
  1466. if (slot.last_nl_pos > 0) {
  1467. size_t pos = slot.last_nl_pos;
  1468. int n_indent = 0;
  1469. while (pos < slot.generated_text.size() && (slot.generated_text[pos] == ' ' || slot.generated_text[pos] == '\t')) {
  1470. n_indent++;
  1471. pos++;
  1472. }
  1473. if (pos < slot.generated_text.size() && n_indent < slot.params.n_indent) {
  1474. slot.stop = STOP_TYPE_LIMIT;
  1475. slot.has_next_token = false;
  1476. // cut the last line
  1477. slot.generated_text.erase(pos, std::string::npos);
  1478. SLT_DBG(slot, "stopped by indentation limit, n_decoded = %d, n_indent = %d\n", slot.n_decoded, n_indent);
  1479. }
  1480. }
  1481. // find the next new line
  1482. {
  1483. const size_t pos = slot.generated_text.find('\n', slot.last_nl_pos);
  1484. if (pos != std::string::npos) {
  1485. slot.last_nl_pos = pos + 1;
  1486. }
  1487. }
  1488. }
  1489. }
  1490. // check if there is a new line in the generated text
  1491. if (result.text_to_send.find('\n') != std::string::npos) {
  1492. slot.has_new_line = true;
  1493. }
  1494. // if context shift is disabled, we stop when it reaches the context limit
  1495. if (slot.n_past >= slot.n_ctx) {
  1496. slot.truncated = true;
  1497. slot.stop = STOP_TYPE_LIMIT;
  1498. slot.has_next_token = false;
  1499. 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",
  1500. slot.n_decoded, slot.n_prompt_tokens, slot.n_past, slot.n_ctx);
  1501. }
  1502. if (llama_token_is_eog(model, result.tok)) {
  1503. slot.stop = STOP_TYPE_EOS;
  1504. slot.has_next_token = false;
  1505. SLT_DBG(slot, "%s", "stopped by EOS\n");
  1506. }
  1507. const auto n_ctx_train = llama_n_ctx_train(model);
  1508. if (slot.params.n_predict < 1 && slot.n_predict < 1 && slot.n_prompt_tokens + slot.n_decoded >= n_ctx_train) {
  1509. slot.truncated = true;
  1510. slot.stop = STOP_TYPE_LIMIT;
  1511. slot.has_next_token = false; // stop prediction
  1512. SLT_WRN(slot,
  1513. "n_predict (%d) is set for infinite generation. "
  1514. "Limiting generated tokens to n_ctx_train (%d) to avoid EOS-less generation infinite loop\n",
  1515. slot.params.n_predict, n_ctx_train);
  1516. }
  1517. 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());
  1518. return slot.has_next_token; // continue
  1519. }
  1520. void send_error(const server_task & task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1521. send_error(task.id, error, type);
  1522. }
  1523. void send_error(const server_slot & slot, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1524. send_error(slot.id_task, error, type);
  1525. }
  1526. void send_error(const int id_task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1527. SRV_ERR("task id = %d, error: %s\n", id_task, error.c_str());
  1528. auto res = std::make_unique<server_task_result_error>();
  1529. res->id = id_task;
  1530. res->err_type = type;
  1531. res->err_msg = error;
  1532. queue_results.send(std::move(res));
  1533. }
  1534. void send_partial_response(server_slot & slot, const completion_token_output & tkn) {
  1535. auto res = std::make_unique<server_task_result_cmpl_partial>();
  1536. res->id = slot.id_task;
  1537. res->index = slot.index;
  1538. res->content = tkn.text_to_send;
  1539. res->truncated = slot.truncated;
  1540. res->n_decoded = slot.n_decoded;
  1541. res->n_prompt_tokens = slot.n_prompt_tokens;
  1542. res->stop = slot.stop;
  1543. res->verbose = slot.params.verbose;
  1544. res->oaicompat = slot.params.oaicompat;
  1545. res->oaicompat_chat = slot.params.oaicompat_chat;
  1546. res->oaicompat_model = slot.params.oaicompat_model;
  1547. res->oaicompat_cmpl_id = slot.params.oaicompat_cmpl_id;
  1548. // populate res.probs_output
  1549. if (slot.params.sampling.n_probs > 0) {
  1550. const llama_tokens to_send_toks = common_tokenize(ctx, tkn.text_to_send, false);
  1551. const size_t probs_pos = std::min(slot.n_sent_token_probs, slot.generated_token_probs.size());
  1552. const size_t probs_stop_pos = std::min(slot.n_sent_token_probs + to_send_toks.size(), slot.generated_token_probs.size());
  1553. std::vector<completion_token_output> probs_output;
  1554. if (probs_pos < probs_stop_pos) {
  1555. res->probs_output = std::vector<completion_token_output>(
  1556. slot.generated_token_probs.begin() + probs_pos,
  1557. slot.generated_token_probs.begin() + probs_stop_pos);
  1558. }
  1559. }
  1560. // populate timings if this is final response or timings_per_token is enabled
  1561. if (slot.stop != STOP_TYPE_NONE || slot.params.timings_per_token) {
  1562. res->timings = slot.get_timings();
  1563. }
  1564. queue_results.send(std::move(res));
  1565. }
  1566. void send_final_response(server_slot & slot) {
  1567. if (slot.params.stream) {
  1568. // if in stream mode, send the last partial response
  1569. send_partial_response(slot, {0, "", {}});
  1570. return;
  1571. }
  1572. auto res = std::make_unique<server_task_result_cmpl_final>();
  1573. res->id = slot.id_task;
  1574. res->id_slot = slot.id;
  1575. res->index = slot.index;
  1576. res->content = slot.generated_text;
  1577. res->timings = slot.get_timings();
  1578. res->prompt = common_detokenize(ctx, slot.prompt_tokens, true);
  1579. res->truncated = slot.truncated;
  1580. res->n_decoded = slot.n_decoded;
  1581. res->n_prompt_tokens = slot.n_prompt_tokens;
  1582. res->n_tokens_cached = slot.n_past;
  1583. res->has_new_line = slot.has_new_line;
  1584. res->stopping_word = slot.stopping_word;
  1585. res->stop = slot.stop;
  1586. res->verbose = slot.params.verbose;
  1587. res->oaicompat = slot.params.oaicompat;
  1588. res->oaicompat_chat = slot.params.oaicompat_chat;
  1589. res->oaicompat_model = slot.params.oaicompat_model;
  1590. res->oaicompat_cmpl_id = slot.params.oaicompat_cmpl_id;
  1591. // populate res.probs_output
  1592. if (slot.params.sampling.n_probs > 0) {
  1593. if (!slot.params.stream && slot.stop == STOP_TYPE_WORD) {
  1594. const llama_tokens stop_word_toks = common_tokenize(ctx, slot.stopping_word, false);
  1595. size_t safe_offset = std::min(slot.generated_token_probs.size(), stop_word_toks.size());
  1596. res->probs_output = std::vector<completion_token_output>(
  1597. slot.generated_token_probs.begin(),
  1598. slot.generated_token_probs.end() - safe_offset);
  1599. } else {
  1600. res->probs_output = std::vector<completion_token_output>(
  1601. slot.generated_token_probs.begin(),
  1602. slot.generated_token_probs.end());
  1603. }
  1604. }
  1605. res->generation_params = slot.params; // copy the parameters
  1606. queue_results.send(std::move(res));
  1607. }
  1608. void send_embedding(const server_slot & slot, const llama_batch & batch) {
  1609. auto res = std::make_unique<server_task_result_embd>();
  1610. res->id = slot.id_task;
  1611. res->index = slot.index;
  1612. const int n_embd = llama_n_embd(model);
  1613. std::vector<float> embd_res(n_embd, 0.0f);
  1614. for (int i = 0; i < batch.n_tokens; ++i) {
  1615. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  1616. continue;
  1617. }
  1618. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1619. if (embd == NULL) {
  1620. embd = llama_get_embeddings_ith(ctx, i);
  1621. }
  1622. if (embd == NULL) {
  1623. SLT_ERR(slot, "failed to get embeddings, token = %d, seq_id = %d\n", batch.token[i], batch.seq_id[i][0]);
  1624. res->embedding = std::vector<float>(n_embd, 0.0f);
  1625. continue;
  1626. }
  1627. common_embd_normalize(embd, embd_res.data(), n_embd);
  1628. res->embedding = embd_res;
  1629. }
  1630. SLT_DBG(slot, "%s", "sending embeddings\n");
  1631. queue_results.send(std::move(res));
  1632. }
  1633. void send_rerank(const server_slot & slot, const llama_batch & batch) {
  1634. auto res = std::make_unique<server_task_result_rerank>();
  1635. res->id = slot.id_task;
  1636. res->index = slot.index;
  1637. for (int i = 0; i < batch.n_tokens; ++i) {
  1638. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  1639. continue;
  1640. }
  1641. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1642. if (embd == NULL) {
  1643. embd = llama_get_embeddings_ith(ctx, i);
  1644. }
  1645. if (embd == NULL) {
  1646. SLT_ERR(slot, "failed to get embeddings, token = %d, seq_id = %d\n", batch.token[i], batch.seq_id[i][0]);
  1647. res->score = -1e6;
  1648. continue;
  1649. }
  1650. res->score = embd[0];
  1651. }
  1652. SLT_DBG(slot, "sending rerank result, res.score = %f\n", res->score);
  1653. queue_results.send(std::move(res));
  1654. }
  1655. //
  1656. // Functions to create new task(s) and receive result(s)
  1657. //
  1658. // break the input "prompt" into multiple tasks if needed, then format and tokenize the input prompt(s)
  1659. std::vector<server_task> create_tasks_inference(json data, server_task_inf_type inf_type) {
  1660. std::vector<server_task> tasks;
  1661. auto create_task = [&](json & task_data, llama_tokens & prompt_tokens) {
  1662. SRV_DBG("create task, n_tokens = %d\n", (int) prompt_tokens.size());
  1663. server_task task;
  1664. task.id = queue_tasks.get_new_id();
  1665. task.inf_type = inf_type;
  1666. task.type = SERVER_TASK_TYPE_INFERENCE;
  1667. task.data = task_data;
  1668. task.prompt_tokens = std::move(prompt_tokens);
  1669. tasks.push_back(std::move(task));
  1670. };
  1671. static constexpr const char * error_msg = "\"prompt\" must be a string, an array of token ids or an array of prompts";
  1672. if (!data.contains("prompt")) {
  1673. throw std::runtime_error(error_msg);
  1674. }
  1675. // because llama_tokenize api is thread-safe, we can tokenize the prompt from HTTP thread
  1676. bool add_special = inf_type != SERVER_TASK_INF_TYPE_RERANK && inf_type != SERVER_TASK_INF_TYPE_INFILL;
  1677. std::vector<llama_tokens> tokenized_prompts = tokenize_input_prompts(ctx, data.at("prompt"), add_special, true);
  1678. switch (inf_type) {
  1679. case SERVER_TASK_INF_TYPE_RERANK:
  1680. {
  1681. // prompts[0] is the question
  1682. // the rest are the answers/documents
  1683. GGML_ASSERT(tokenized_prompts.size() > 1);
  1684. SRV_DBG("creating rerank tasks, n_prompts = %d\n", (int) tokenized_prompts.size() - 1);
  1685. for (size_t i = 1; i < tokenized_prompts.size(); i++) {
  1686. data["index"] = i - 1;
  1687. auto tokens = format_rerank(model, tokenized_prompts[0], tokenized_prompts[i]);
  1688. create_task(data, tokens);
  1689. }
  1690. } break;
  1691. case SERVER_TASK_INF_TYPE_INFILL:
  1692. {
  1693. SRV_DBG("creating infill tasks, n_prompts = %d\n", (int) tokenized_prompts.size());
  1694. for (size_t i = 0; i < tokenized_prompts.size(); i++) {
  1695. data["index"] = i;
  1696. auto tokens = format_infill(
  1697. ctx,
  1698. data.at("input_prefix"),
  1699. data.at("input_suffix"),
  1700. data.at("input_extra"),
  1701. params_base.n_batch,
  1702. params_base.n_predict,
  1703. slots[0].n_ctx, // TODO: there should be a better way
  1704. params_base.spm_infill,
  1705. tokenized_prompts[i]
  1706. );
  1707. create_task(data, tokens);
  1708. }
  1709. } break;
  1710. default:
  1711. {
  1712. SRV_DBG("creating multi-prompt tasks, n_prompts = %d\n", (int) tokenized_prompts.size());
  1713. for (size_t i = 0; i < tokenized_prompts.size(); i++) {
  1714. data["index"] = i;
  1715. create_task(data, tokenized_prompts[i]);
  1716. }
  1717. }
  1718. }
  1719. return tasks;
  1720. }
  1721. void cancel_tasks(const std::unordered_set<int> & id_tasks) {
  1722. std::vector<server_task> cancel_tasks;
  1723. cancel_tasks.reserve(id_tasks.size());
  1724. for (const auto & id_task : id_tasks) {
  1725. SRV_WRN("cancel task, id_task = %d\n", id_task);
  1726. server_task task;
  1727. task.type = SERVER_TASK_TYPE_CANCEL;
  1728. task.id_target = id_task;
  1729. cancel_tasks.push_back(task);
  1730. queue_results.remove_waiting_task_id(id_task);
  1731. }
  1732. // push to beginning of the queue, so it has highest priority
  1733. queue_tasks.post(cancel_tasks, true);
  1734. }
  1735. // receive the results from task(s) created by create_tasks_inference
  1736. void receive_multi_results(
  1737. const std::unordered_set<int> & id_tasks,
  1738. const std::function<void(std::vector<server_task_result_ptr>&)> & result_handler,
  1739. const std::function<void(json)> & error_handler) {
  1740. std::vector<server_task_result_ptr> results(id_tasks.size());
  1741. for (size_t i = 0; i < id_tasks.size(); i++) {
  1742. server_task_result_ptr result = queue_results.recv(id_tasks);
  1743. if (result->is_error()) {
  1744. error_handler(result->to_json());
  1745. cancel_tasks(id_tasks);
  1746. return;
  1747. }
  1748. GGML_ASSERT(
  1749. dynamic_cast<server_task_result_cmpl_final*>(result.get()) != nullptr
  1750. || dynamic_cast<server_task_result_embd*>(result.get()) != nullptr
  1751. || dynamic_cast<server_task_result_rerank*>(result.get()) != nullptr
  1752. );
  1753. const size_t idx = result->get_index();
  1754. GGML_ASSERT(idx < results.size() && "index out of range");
  1755. results[idx] = std::move(result);
  1756. }
  1757. result_handler(results);
  1758. }
  1759. // receive the results from task(s) created by create_tasks_inference, in stream mode
  1760. void receive_cmpl_results_stream(
  1761. const std::unordered_set<int> & id_tasks,
  1762. const std::function<bool(server_task_result_ptr&)> & result_handler,
  1763. const std::function<void(json)> & error_handler) {
  1764. size_t n_finished = 0;
  1765. while (true) {
  1766. server_task_result_ptr result = queue_results.recv(id_tasks);
  1767. if (result->is_error()) {
  1768. error_handler(result->to_json());
  1769. cancel_tasks(id_tasks);
  1770. return;
  1771. }
  1772. GGML_ASSERT(dynamic_cast<server_task_result_cmpl_partial*>(result.get()) != nullptr);
  1773. if (!result_handler(result)) {
  1774. cancel_tasks(id_tasks);
  1775. break;
  1776. }
  1777. if (result->is_stop()) {
  1778. if (++n_finished == id_tasks.size()) {
  1779. break;
  1780. }
  1781. }
  1782. }
  1783. }
  1784. //
  1785. // Functions to process the task
  1786. //
  1787. void process_single_task(server_task task) {
  1788. switch (task.type) {
  1789. case SERVER_TASK_TYPE_INFERENCE:
  1790. {
  1791. const int id_slot = json_value(task.data, "id_slot", -1);
  1792. server_slot * slot = id_slot != -1 ? get_slot_by_id(id_slot) : get_available_slot(task);
  1793. if (slot == nullptr) {
  1794. // if no slot is available, we defer this task for processing later
  1795. SRV_DBG("no slot is available, defer task, id_task = %d\n", task.id);
  1796. queue_tasks.defer(task);
  1797. break;
  1798. }
  1799. if (slot->is_processing()) {
  1800. // if requested slot is unavailable, we defer this task for processing later
  1801. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1802. queue_tasks.defer(task);
  1803. break;
  1804. }
  1805. slot->reset();
  1806. slot->id_task = task.id;
  1807. slot->inf_type = task.inf_type;
  1808. slot->index = json_value(task.data, "index", 0);
  1809. slot->prompt_tokens = std::move(task.prompt_tokens);
  1810. if (!launch_slot_with_task(*slot, task)) {
  1811. SRV_ERR("failed to launch slot with task, id_task = %d\n", task.id);
  1812. break;
  1813. }
  1814. } break;
  1815. case SERVER_TASK_TYPE_CANCEL:
  1816. {
  1817. // release slot linked with the task id
  1818. for (auto & slot : slots) {
  1819. if (slot.id_task == task.id_target) {
  1820. slot.release();
  1821. break;
  1822. }
  1823. }
  1824. } break;
  1825. case SERVER_TASK_TYPE_NEXT_RESPONSE:
  1826. {
  1827. // do nothing
  1828. } break;
  1829. case SERVER_TASK_TYPE_METRICS:
  1830. {
  1831. json slots_data = json::array();
  1832. int n_idle_slots = 0;
  1833. int n_processing_slots = 0;
  1834. for (server_slot & slot : slots) {
  1835. json slot_data = slot.to_json();
  1836. if (slot.is_processing()) {
  1837. n_processing_slots++;
  1838. } else {
  1839. n_idle_slots++;
  1840. }
  1841. slots_data.push_back(slot_data);
  1842. }
  1843. SRV_DBG("n_idle_slots = %d, n_processing_slots = %d\n", n_idle_slots, n_processing_slots);
  1844. auto res = std::make_unique<server_task_result_metrics>();
  1845. res->id = task.id;
  1846. res->slots_data = std::move(slots_data);
  1847. res->n_idle_slots = n_idle_slots;
  1848. res->n_processing_slots = n_processing_slots;
  1849. res->n_tasks_deferred = queue_tasks.queue_tasks_deferred.size();
  1850. res->t_start = metrics.t_start;
  1851. res->kv_cache_tokens_count = llama_get_kv_cache_token_count(ctx);
  1852. res->kv_cache_used_cells = llama_get_kv_cache_used_cells(ctx);
  1853. res->n_prompt_tokens_processed_total = metrics.n_prompt_tokens_processed_total;
  1854. res->t_prompt_processing_total = metrics.t_prompt_processing_total;
  1855. res->n_tokens_predicted_total = metrics.n_tokens_predicted_total;
  1856. res->t_tokens_generation_total = metrics.t_tokens_generation_total;
  1857. res->n_prompt_tokens_processed = metrics.n_prompt_tokens_processed;
  1858. res->t_prompt_processing = metrics.t_prompt_processing;
  1859. res->n_tokens_predicted = metrics.n_tokens_predicted;
  1860. res->t_tokens_generation = metrics.t_tokens_generation;
  1861. res->n_decode_total = metrics.n_decode_total;
  1862. res->n_busy_slots_total = metrics.n_busy_slots_total;
  1863. if (json_value(task.data, "reset_bucket", false)) {
  1864. metrics.reset_bucket();
  1865. }
  1866. queue_results.send(std::move(res));
  1867. } break;
  1868. case SERVER_TASK_TYPE_SLOT_SAVE:
  1869. {
  1870. int id_slot = task.data.at("id_slot");
  1871. server_slot * slot = get_slot_by_id(id_slot);
  1872. if (slot == nullptr) {
  1873. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1874. break;
  1875. }
  1876. if (slot->is_processing()) {
  1877. // if requested slot is unavailable, we defer this task for processing later
  1878. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1879. queue_tasks.defer(task);
  1880. break;
  1881. }
  1882. const size_t token_count = slot->cache_tokens.size();
  1883. const int64_t t_start = ggml_time_us();
  1884. std::string filename = task.data.at("filename");
  1885. std::string filepath = task.data.at("filepath");
  1886. const size_t nwrite = llama_state_seq_save_file(ctx, filepath.c_str(), slot->id, slot->cache_tokens.data(), token_count);
  1887. const int64_t t_end = ggml_time_us();
  1888. const double t_save_ms = (t_end - t_start) / 1000.0;
  1889. auto res = std::make_unique<server_task_result_slot_save_load>();
  1890. res->id = task.id;
  1891. res->id_slot = id_slot;
  1892. res->filename = filename;
  1893. res->is_save = true;
  1894. res->n_tokens = token_count;
  1895. res->n_bytes = nwrite;
  1896. res->t_ms = t_save_ms;
  1897. queue_results.send(std::move(res));
  1898. } break;
  1899. case SERVER_TASK_TYPE_SLOT_RESTORE:
  1900. {
  1901. int id_slot = task.data.at("id_slot");
  1902. server_slot * slot = get_slot_by_id(id_slot);
  1903. if (slot == nullptr) {
  1904. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1905. break;
  1906. }
  1907. if (slot->is_processing()) {
  1908. // if requested slot is unavailable, we defer this task for processing later
  1909. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1910. queue_tasks.defer(task);
  1911. break;
  1912. }
  1913. const int64_t t_start = ggml_time_us();
  1914. std::string filename = task.data.at("filename");
  1915. std::string filepath = task.data.at("filepath");
  1916. slot->cache_tokens.resize(slot->n_ctx);
  1917. size_t token_count = 0;
  1918. size_t nread = llama_state_seq_load_file(ctx, filepath.c_str(), slot->id, slot->cache_tokens.data(), slot->cache_tokens.size(), &token_count);
  1919. if (nread == 0) {
  1920. slot->cache_tokens.resize(0);
  1921. send_error(task, "Unable to restore slot, no available space in KV cache or invalid slot save file", ERROR_TYPE_INVALID_REQUEST);
  1922. break;
  1923. }
  1924. slot->cache_tokens.resize(token_count);
  1925. const int64_t t_end = ggml_time_us();
  1926. const double t_restore_ms = (t_end - t_start) / 1000.0;
  1927. auto res = std::make_unique<server_task_result_slot_save_load>();
  1928. res->id = task.id;
  1929. res->id_slot = id_slot;
  1930. res->filename = filename;
  1931. res->is_save = false;
  1932. res->n_tokens = token_count;
  1933. res->n_bytes = nread;
  1934. res->t_ms = t_restore_ms;
  1935. queue_results.send(std::move(res));
  1936. } break;
  1937. case SERVER_TASK_TYPE_SLOT_ERASE:
  1938. {
  1939. int id_slot = task.data.at("id_slot");
  1940. server_slot * slot = get_slot_by_id(id_slot);
  1941. if (slot == nullptr) {
  1942. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1943. break;
  1944. }
  1945. if (slot->is_processing()) {
  1946. // if requested slot is unavailable, we defer this task for processing later
  1947. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1948. queue_tasks.defer(task);
  1949. break;
  1950. }
  1951. // Erase token cache
  1952. const size_t n_erased = slot->cache_tokens.size();
  1953. llama_kv_cache_seq_rm(ctx, slot->id, -1, -1);
  1954. slot->cache_tokens.clear();
  1955. auto res = std::make_unique<server_task_result_slot_erase>();
  1956. res->id = task.id;
  1957. res->id_slot = id_slot;
  1958. res->n_erased = n_erased;
  1959. queue_results.send(std::move(res));
  1960. } break;
  1961. case SERVER_TASK_TYPE_SET_LORA:
  1962. {
  1963. common_lora_adapters_apply(ctx, loras);
  1964. auto res = std::make_unique<server_task_result_apply_lora>();
  1965. res->id = task.id;
  1966. queue_results.send(std::move(res));
  1967. } break;
  1968. }
  1969. }
  1970. void update_slots() {
  1971. // check if all slots are idle
  1972. {
  1973. bool all_idle = true;
  1974. for (auto & slot : slots) {
  1975. if (slot.is_processing()) {
  1976. all_idle = false;
  1977. break;
  1978. }
  1979. }
  1980. if (all_idle) {
  1981. SRV_INF("%s", "all slots are idle\n");
  1982. if (clean_kv_cache) {
  1983. kv_cache_clear();
  1984. }
  1985. return;
  1986. }
  1987. }
  1988. {
  1989. SRV_DBG("%s", "posting NEXT_RESPONSE\n");
  1990. server_task task;
  1991. task.type = SERVER_TASK_TYPE_NEXT_RESPONSE;
  1992. task.id_target = -1;
  1993. queue_tasks.post(task);
  1994. }
  1995. // apply context-shift if needed
  1996. // TODO: simplify and improve
  1997. for (server_slot & slot : slots) {
  1998. if (slot.is_processing() && slot.n_past + 1 >= slot.n_ctx) {
  1999. if (!params_base.ctx_shift) {
  2000. // this check is redundant (for good)
  2001. // we should never get here, because generation should already stopped in process_token()
  2002. slot.release();
  2003. send_error(slot, "context shift is disabled", ERROR_TYPE_SERVER);
  2004. continue;
  2005. }
  2006. // Shift context
  2007. const int n_keep = slot.params.n_keep + add_bos_token;
  2008. const int n_left = slot.n_past - n_keep;
  2009. const int n_discard = slot.params.n_discard ? slot.params.n_discard : (n_left / 2);
  2010. SLT_WRN(slot, "slot context shift, n_keep = %d, n_left = %d, n_discard = %d\n", n_keep, n_left, n_discard);
  2011. llama_kv_cache_seq_rm (ctx, slot.id, n_keep , n_keep + n_discard);
  2012. llama_kv_cache_seq_add(ctx, slot.id, n_keep + n_discard, slot.n_past, -n_discard);
  2013. if (slot.params.cache_prompt) {
  2014. for (size_t i = n_keep + n_discard; i < slot.cache_tokens.size(); i++) {
  2015. slot.cache_tokens[i - n_discard] = slot.cache_tokens[i];
  2016. }
  2017. slot.cache_tokens.resize(slot.cache_tokens.size() - n_discard);
  2018. }
  2019. slot.n_past -= n_discard;
  2020. slot.truncated = true;
  2021. }
  2022. }
  2023. // start populating the batch for this iteration
  2024. common_batch_clear(batch);
  2025. // frist, add sampled tokens from any ongoing sequences
  2026. for (auto & slot : slots) {
  2027. if (slot.state != SLOT_STATE_GENERATING) {
  2028. continue;
  2029. }
  2030. slot.i_batch = batch.n_tokens;
  2031. common_batch_add(batch, slot.sampled, slot.n_past, { slot.id }, true);
  2032. slot.n_past += 1;
  2033. if (slot.params.cache_prompt) {
  2034. slot.cache_tokens.push_back(slot.sampled);
  2035. }
  2036. SLT_DBG(slot, "slot decode token, n_ctx = %d, n_past = %d, n_cache_tokens = %d, truncated = %d\n",
  2037. slot.n_ctx, slot.n_past, (int) slot.cache_tokens.size(), slot.truncated);
  2038. }
  2039. // process in chunks of params.n_batch
  2040. int32_t n_batch = llama_n_batch(ctx);
  2041. int32_t n_ubatch = llama_n_ubatch(ctx);
  2042. // track if this is an embedding or non-embedding batch
  2043. // if we've added sampled tokens above, we are in non-embedding mode
  2044. // -1: none, 0: non-embedding, 1: embedding
  2045. // TODO: make enum
  2046. int32_t batch_type = batch.n_tokens > 0 ? 0 : -1;
  2047. // next, batch any pending prompts without exceeding n_batch
  2048. if (params_base.cont_batching || batch.n_tokens == 0) {
  2049. for (auto & slot : slots) {
  2050. // this slot still has a prompt to be processed
  2051. if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_STARTED) {
  2052. auto & prompt_tokens = slot.prompt_tokens;
  2053. // TODO: maybe move branch to outside of this loop in the future
  2054. if (slot.state == SLOT_STATE_STARTED) {
  2055. slot.t_start_process_prompt = ggml_time_us();
  2056. slot.t_start_generation = 0;
  2057. slot.n_past = 0;
  2058. slot.n_prompt_tokens = prompt_tokens.size();
  2059. slot.state = SLOT_STATE_PROCESSING_PROMPT;
  2060. 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);
  2061. // print prompt tokens (for debugging)
  2062. if (1) {
  2063. // first 16 tokens (avoid flooding logs)
  2064. for (int i = 0; i < std::min<int>(16, prompt_tokens.size()); i++) {
  2065. SLT_DBG(slot, "prompt token %3d: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  2066. }
  2067. } else {
  2068. // all
  2069. for (int i = 0; i < (int) prompt_tokens.size(); i++) {
  2070. SLT_DBG(slot, "prompt token %3d: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  2071. }
  2072. }
  2073. // empty prompt passed -> release the slot and send empty response
  2074. if (prompt_tokens.empty()) {
  2075. SLT_WRN(slot, "%s", "empty prompt - releasing slot\n");
  2076. slot.release();
  2077. slot.print_timings();
  2078. send_final_response(slot);
  2079. continue;
  2080. }
  2081. if (slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING || slot.inf_type == SERVER_TASK_INF_TYPE_RERANK) {
  2082. if (slot.n_prompt_tokens > n_ubatch) {
  2083. slot.release();
  2084. send_error(slot, "input is too large to process. increase the physical batch size", ERROR_TYPE_SERVER);
  2085. continue;
  2086. }
  2087. if (slot.n_prompt_tokens > slot.n_ctx) {
  2088. slot.release();
  2089. send_error(slot, "input is larger than the max context size. skipping", ERROR_TYPE_SERVER);
  2090. continue;
  2091. }
  2092. } else {
  2093. if (!params_base.ctx_shift) {
  2094. // if context shift is disabled, we make sure prompt size is smaller than KV size
  2095. // TODO: there should be a separate parameter that control prompt truncation
  2096. // context shift should be applied only during the generation phase
  2097. if (slot.n_prompt_tokens >= slot.n_ctx) {
  2098. slot.release();
  2099. send_error(slot, "the request exceeds the available context size. try increasing the context size or enable context shift", ERROR_TYPE_INVALID_REQUEST);
  2100. continue;
  2101. }
  2102. }
  2103. if (slot.params.n_keep < 0) {
  2104. slot.params.n_keep = slot.n_prompt_tokens;
  2105. }
  2106. slot.params.n_keep = std::min(slot.n_ctx - 4, slot.params.n_keep);
  2107. // if input prompt is too big, truncate it
  2108. if (slot.n_prompt_tokens >= slot.n_ctx) {
  2109. const int n_left = slot.n_ctx - slot.params.n_keep;
  2110. const int n_block_size = n_left / 2;
  2111. const int erased_blocks = (slot.n_prompt_tokens - slot.params.n_keep - n_block_size) / n_block_size;
  2112. llama_tokens new_tokens(
  2113. prompt_tokens.begin(),
  2114. prompt_tokens.begin() + slot.params.n_keep);
  2115. new_tokens.insert(
  2116. new_tokens.end(),
  2117. prompt_tokens.begin() + slot.params.n_keep + erased_blocks * n_block_size,
  2118. prompt_tokens.end());
  2119. prompt_tokens = std::move(new_tokens);
  2120. slot.truncated = true;
  2121. slot.n_prompt_tokens = prompt_tokens.size();
  2122. 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);
  2123. GGML_ASSERT(slot.n_prompt_tokens < slot.n_ctx);
  2124. }
  2125. if (slot.params.cache_prompt) {
  2126. // reuse any previously computed tokens that are common with the new prompt
  2127. slot.n_past = common_lcp(slot.cache_tokens, prompt_tokens);
  2128. // reuse chunks from the cached prompt by shifting their KV cache in the new position
  2129. if (params_base.n_cache_reuse > 0) {
  2130. size_t head_c = slot.n_past; // cache
  2131. size_t head_p = slot.n_past; // current prompt
  2132. SLT_DBG(slot, "trying to reuse chunks with size > %d, slot.n_past = %d\n", params_base.n_cache_reuse, slot.n_past);
  2133. while (head_c < slot.cache_tokens.size() &&
  2134. head_p < prompt_tokens.size()) {
  2135. size_t n_match = 0;
  2136. while (head_c + n_match < slot.cache_tokens.size() &&
  2137. head_p + n_match < prompt_tokens.size() &&
  2138. slot.cache_tokens[head_c + n_match] == prompt_tokens[head_p + n_match]) {
  2139. n_match++;
  2140. }
  2141. if (n_match >= (size_t) params_base.n_cache_reuse) {
  2142. 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);
  2143. //for (size_t i = head_p; i < head_p + n_match; i++) {
  2144. // SLT_DBG(slot, "cache token %3zu: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  2145. //}
  2146. const int64_t kv_shift = (int64_t) head_p - (int64_t) head_c;
  2147. llama_kv_cache_seq_rm (ctx, slot.id, head_p, head_c);
  2148. llama_kv_cache_seq_add(ctx, slot.id, head_c, -1, kv_shift);
  2149. for (size_t i = 0; i < n_match; i++) {
  2150. slot.cache_tokens[head_p + i] = slot.cache_tokens[head_c + i];
  2151. slot.n_past++;
  2152. }
  2153. head_c += n_match;
  2154. head_p += n_match;
  2155. } else {
  2156. head_c += 1;
  2157. }
  2158. }
  2159. SLT_DBG(slot, "after context reuse, new slot.n_past = %d\n", slot.n_past);
  2160. }
  2161. }
  2162. }
  2163. if (slot.n_past == slot.n_prompt_tokens && slot.n_past > 0) {
  2164. // we have to evaluate at least 1 token to generate logits.
  2165. SLT_WRN(slot, "need to evaluate at least 1 token to generate logits, n_past = %d, n_prompt_tokens = %d\n", slot.n_past, slot.n_prompt_tokens);
  2166. slot.n_past--;
  2167. }
  2168. slot.n_prompt_tokens_processed = 0;
  2169. }
  2170. // non-causal tasks require to fit the entire prompt in the physical batch
  2171. if (slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING || slot.inf_type == SERVER_TASK_INF_TYPE_RERANK) {
  2172. // cannot fit the prompt in the current batch - will try next iter
  2173. if (batch.n_tokens + slot.n_prompt_tokens > n_batch) {
  2174. continue;
  2175. }
  2176. }
  2177. // check that we are in the right batch_type, if not defer the slot
  2178. const bool slot_type =
  2179. slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING ||
  2180. slot.inf_type == SERVER_TASK_INF_TYPE_RERANK ? 1 : 0;
  2181. if (batch_type == -1) {
  2182. batch_type = slot_type;
  2183. } else if (batch_type != slot_type) {
  2184. continue;
  2185. }
  2186. // keep only the common part
  2187. if (!llama_kv_cache_seq_rm(ctx, slot.id, slot.n_past, -1)) {
  2188. // could not partially delete (likely using a non-Transformer model)
  2189. llama_kv_cache_seq_rm(ctx, slot.id, -1, -1);
  2190. // there is no common part left
  2191. slot.n_past = 0;
  2192. }
  2193. SLT_INF(slot, "kv cache rm [%d, end)\n", slot.n_past);
  2194. // remove the non-common part from the cache
  2195. slot.cache_tokens.resize(slot.n_past);
  2196. // add prompt tokens for processing in the current batch
  2197. while (slot.n_past < slot.n_prompt_tokens && batch.n_tokens < n_batch) {
  2198. common_batch_add(batch, prompt_tokens[slot.n_past], slot.n_past, { slot.id }, false);
  2199. if (slot.params.cache_prompt) {
  2200. slot.cache_tokens.push_back(prompt_tokens[slot.n_past]);
  2201. }
  2202. slot.n_prompt_tokens_processed++;
  2203. slot.n_past++;
  2204. }
  2205. 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);
  2206. // entire prompt has been processed
  2207. if (slot.n_past == slot.n_prompt_tokens) {
  2208. slot.state = SLOT_STATE_DONE_PROMPT;
  2209. GGML_ASSERT(batch.n_tokens > 0);
  2210. common_sampler_reset(slot.smpl);
  2211. // Process all prompt tokens through sampler system
  2212. for (int i = 0; i < slot.n_prompt_tokens; ++i) {
  2213. common_sampler_accept(slot.smpl, prompt_tokens[i], false);
  2214. }
  2215. // extract the logits only for the last token
  2216. batch.logits[batch.n_tokens - 1] = true;
  2217. slot.n_decoded = 0;
  2218. slot.i_batch = batch.n_tokens - 1;
  2219. SLT_INF(slot, "prompt done, n_past = %d, n_tokens = %d\n", slot.n_past, batch.n_tokens);
  2220. }
  2221. }
  2222. if (batch.n_tokens >= n_batch) {
  2223. break;
  2224. }
  2225. }
  2226. }
  2227. if (batch.n_tokens == 0) {
  2228. SRV_WRN("%s", "no tokens to decode\n");
  2229. return;
  2230. }
  2231. SRV_DBG("decoding batch, n_tokens = %d\n", batch.n_tokens);
  2232. // make sure we're in the right embedding mode
  2233. llama_set_embeddings(ctx, batch_type == 1);
  2234. // process the created batch of tokens
  2235. for (int32_t i = 0; i < batch.n_tokens; i += n_batch) {
  2236. const int32_t n_tokens = std::min(n_batch, batch.n_tokens - i);
  2237. llama_batch batch_view = {
  2238. n_tokens,
  2239. batch.token + i,
  2240. nullptr,
  2241. batch.pos + i,
  2242. batch.n_seq_id + i,
  2243. batch.seq_id + i,
  2244. batch.logits + i,
  2245. };
  2246. const int ret = llama_decode(ctx, batch_view);
  2247. metrics.on_decoded(slots);
  2248. if (ret != 0) {
  2249. if (n_batch == 1 || ret < 0) {
  2250. // if you get here, it means the KV cache is full - try increasing it via the context size
  2251. SRV_ERR("failed to decode the batch: KV cache is full - try increasing it via the context size, i = %d, n_batch = %d, ret = %d\n", i, n_batch, ret);
  2252. for (auto & slot : slots) {
  2253. slot.release();
  2254. send_error(slot, "Input prompt is too big compared to KV size. Please try increasing KV size.");
  2255. }
  2256. break; // break loop of n_batch
  2257. }
  2258. // retry with half the batch size to try to find a free slot in the KV cache
  2259. n_batch /= 2;
  2260. i -= n_batch;
  2261. SRV_WRN("failed to find free space in the KV cache, retrying with smaller batch size - try increasing it via the context size or enable defragmentation, i = %d, n_batch = %d, ret = %d\n", i, n_batch, ret);
  2262. continue; // continue loop of n_batch
  2263. }
  2264. for (auto & slot : slots) {
  2265. if (slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens)) {
  2266. continue; // continue loop of slots
  2267. }
  2268. if (slot.state == SLOT_STATE_DONE_PROMPT) {
  2269. if (slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING) {
  2270. // prompt evaluated for embedding
  2271. send_embedding(slot, batch_view);
  2272. slot.release();
  2273. slot.i_batch = -1;
  2274. continue; // continue loop of slots
  2275. }
  2276. if (slot.inf_type == SERVER_TASK_INF_TYPE_RERANK) {
  2277. send_rerank(slot, batch_view);
  2278. slot.release();
  2279. slot.i_batch = -1;
  2280. continue; // continue loop of slots
  2281. }
  2282. // prompt evaluated for next-token prediction
  2283. slot.state = SLOT_STATE_GENERATING;
  2284. } else if (slot.state != SLOT_STATE_GENERATING) {
  2285. continue; // continue loop of slots
  2286. }
  2287. llama_token id = common_sampler_sample(slot.smpl, ctx, slot.i_batch - i);
  2288. slot.i_batch = -1;
  2289. common_sampler_accept(slot.smpl, id, true);
  2290. slot.n_decoded += 1;
  2291. const int64_t t_current = ggml_time_us();
  2292. if (slot.n_decoded == 1) {
  2293. slot.t_start_generation = t_current;
  2294. slot.t_prompt_processing = (slot.t_start_generation - slot.t_start_process_prompt) / 1e3;
  2295. metrics.on_prompt_eval(slot);
  2296. }
  2297. slot.t_token_generation = (t_current - slot.t_start_generation) / 1e3;
  2298. completion_token_output result;
  2299. result.tok = id;
  2300. const auto * cur_p = common_sampler_get_candidates(slot.smpl);
  2301. for (size_t i = 0; i < (size_t) slot.params.sampling.n_probs; ++i) {
  2302. auto tok_id = cur_p->data[i].id;
  2303. result.probs.push_back({
  2304. tok_id,
  2305. tokens_to_output_formatted_string(ctx, tok_id),
  2306. i >= cur_p->size ? 0.0f : cur_p->data[i].p,
  2307. });
  2308. }
  2309. if (!process_token(result, slot)) {
  2310. // release slot because of stop condition
  2311. slot.release();
  2312. slot.print_timings();
  2313. send_final_response(slot);
  2314. metrics.on_prediction(slot);
  2315. continue;
  2316. }
  2317. }
  2318. // do speculative decoding
  2319. for (auto & slot : slots) {
  2320. if (!slot.is_processing() || !slot.can_speculate()) {
  2321. continue;
  2322. }
  2323. if (slot.state != SLOT_STATE_GENERATING) {
  2324. continue;
  2325. }
  2326. // determine the max draft that fits the current slot state
  2327. int n_draft_max = slot.params.speculative.n_max;
  2328. // note: n_past is not yet increased for the `id` token sampled above
  2329. // also, need to leave space for 1 extra token to allow context shifts
  2330. n_draft_max = std::min(n_draft_max, slot.n_ctx - slot.n_past - 2);
  2331. if (slot.n_remaining > 0) {
  2332. n_draft_max = std::min(n_draft_max, slot.n_remaining - 1);
  2333. }
  2334. SLT_DBG(slot, "max possible draft: %d\n", n_draft_max);
  2335. if (n_draft_max < slot.params.speculative.n_min) {
  2336. SLT_DBG(slot, "the max possible draft is too small: %d < %d - skipping speculative decoding\n", n_draft_max, slot.params.speculative.n_min);
  2337. continue;
  2338. }
  2339. llama_token id = slot.sampled;
  2340. struct common_speculative_params params_spec;
  2341. params_spec.n_draft = n_draft_max;
  2342. params_spec.n_reuse = llama_n_ctx(slot.ctx_dft) - slot.params.speculative.n_max;
  2343. params_spec.p_min = slot.params.speculative.p_min;
  2344. llama_tokens draft = common_speculative_gen_draft(slot.spec, params_spec, slot.cache_tokens, id);
  2345. // ignore small drafts
  2346. if (slot.params.speculative.n_min > (int) draft.size()) {
  2347. SLT_DBG(slot, "ignoring small draft: %d < %d\n", (int) draft.size(), slot.params.speculative.n_min);
  2348. continue;
  2349. }
  2350. // construct the speculation batch
  2351. common_batch_clear(slot.batch_spec);
  2352. common_batch_add (slot.batch_spec, id, slot.n_past, { slot.id }, true);
  2353. for (size_t i = 0; i < draft.size(); ++i) {
  2354. common_batch_add(slot.batch_spec, draft[i], slot.n_past + 1 + i, { slot.id }, true);
  2355. }
  2356. SLT_DBG(slot, "decoding speculative batch, size = %d\n", slot.batch_spec.n_tokens);
  2357. llama_decode(ctx, slot.batch_spec);
  2358. // the accepted tokens from the speculation
  2359. const auto ids = common_sampler_sample_and_accept_n(slot.smpl, ctx, draft);
  2360. slot.n_past += ids.size();
  2361. slot.n_decoded += ids.size();
  2362. slot.cache_tokens.push_back(id);
  2363. slot.cache_tokens.insert(slot.cache_tokens.end(), ids.begin(), ids.end() - 1);
  2364. llama_kv_cache_seq_rm(ctx, slot.id, slot.n_past, -1);
  2365. for (size_t i = 0; i < ids.size(); ++i) {
  2366. completion_token_output result;
  2367. result.tok = ids[i];
  2368. if (!process_token(result, slot)) {
  2369. // release slot because of stop condition
  2370. slot.release();
  2371. slot.print_timings();
  2372. send_final_response(slot);
  2373. metrics.on_prediction(slot);
  2374. break;
  2375. }
  2376. }
  2377. SLT_DBG(slot, "accepted %d/%d draft tokens, new n_past = %d\n", (int) ids.size() - 1, (int) draft.size(), slot.n_past);
  2378. }
  2379. }
  2380. SRV_DBG("%s", "run slots completed\n");
  2381. }
  2382. json model_meta() const {
  2383. return json {
  2384. {"vocab_type", llama_vocab_type (model)},
  2385. {"n_vocab", llama_n_vocab (model)},
  2386. {"n_ctx_train", llama_n_ctx_train (model)},
  2387. {"n_embd", llama_n_embd (model)},
  2388. {"n_params", llama_model_n_params(model)},
  2389. {"size", llama_model_size (model)},
  2390. };
  2391. }
  2392. };
  2393. static void log_server_request(const httplib::Request & req, const httplib::Response & res) {
  2394. // skip GH copilot requests when using default port
  2395. if (req.path == "/v1/health" || req.path == "/v1/completions") {
  2396. return;
  2397. }
  2398. LOG_INF("request: %s %s %s %d\n", req.method.c_str(), req.path.c_str(), req.remote_addr.c_str(), res.status);
  2399. LOG_DBG("request: %s\n", req.body.c_str());
  2400. LOG_DBG("response: %s\n", res.body.c_str());
  2401. }
  2402. std::function<void(int)> shutdown_handler;
  2403. std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
  2404. inline void signal_handler(int signal) {
  2405. if (is_terminating.test_and_set()) {
  2406. // in case it hangs, we can force terminate the server by hitting Ctrl+C twice
  2407. // this is for better developer experience, we can remove when the server is stable enough
  2408. fprintf(stderr, "Received second interrupt, terminating immediately.\n");
  2409. exit(1);
  2410. }
  2411. shutdown_handler(signal);
  2412. }
  2413. int main(int argc, char ** argv) {
  2414. // own arguments required by this example
  2415. common_params params;
  2416. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_SERVER)) {
  2417. return 1;
  2418. }
  2419. common_init();
  2420. // struct that contains llama context and inference
  2421. server_context ctx_server;
  2422. llama_backend_init();
  2423. llama_numa_init(params.numa);
  2424. 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());
  2425. LOG_INF("\n");
  2426. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  2427. LOG_INF("\n");
  2428. std::unique_ptr<httplib::Server> svr;
  2429. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2430. if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
  2431. LOG_INF("Running with SSL: key = %s, cert = %s\n", params.ssl_file_key.c_str(), params.ssl_file_cert.c_str());
  2432. svr.reset(
  2433. new httplib::SSLServer(params.ssl_file_cert.c_str(), params.ssl_file_key.c_str())
  2434. );
  2435. } else {
  2436. LOG_INF("Running without SSL\n");
  2437. svr.reset(new httplib::Server());
  2438. }
  2439. #else
  2440. if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
  2441. LOG_ERR("Server is built without SSL support\n");
  2442. return 1;
  2443. }
  2444. svr.reset(new httplib::Server());
  2445. #endif
  2446. std::atomic<server_state> state{SERVER_STATE_LOADING_MODEL};
  2447. svr->set_default_headers({{"Server", "llama.cpp"}});
  2448. svr->set_logger(log_server_request);
  2449. auto res_error = [](httplib::Response & res, const json & error_data) {
  2450. json final_response {{"error", error_data}};
  2451. res.set_content(final_response.dump(-1, ' ', false, json::error_handler_t::replace), MIMETYPE_JSON);
  2452. res.status = json_value(error_data, "code", 500);
  2453. };
  2454. auto res_ok = [](httplib::Response & res, const json & data) {
  2455. res.set_content(data.dump(-1, ' ', false, json::error_handler_t::replace), MIMETYPE_JSON);
  2456. res.status = 200;
  2457. };
  2458. svr->set_exception_handler([&res_error](const httplib::Request &, httplib::Response & res, const std::exception_ptr & ep) {
  2459. std::string message;
  2460. try {
  2461. std::rethrow_exception(ep);
  2462. } catch (const std::exception & e) {
  2463. message = e.what();
  2464. } catch (...) {
  2465. message = "Unknown Exception";
  2466. }
  2467. json formatted_error = format_error_response(message, ERROR_TYPE_SERVER);
  2468. LOG_WRN("got exception: %s\n", formatted_error.dump().c_str());
  2469. res_error(res, formatted_error);
  2470. });
  2471. svr->set_error_handler([&res_error](const httplib::Request &, httplib::Response & res) {
  2472. if (res.status == 404) {
  2473. res_error(res, format_error_response("File Not Found", ERROR_TYPE_NOT_FOUND));
  2474. }
  2475. // for other error codes, we skip processing here because it's already done by res_error()
  2476. });
  2477. // set timeouts and change hostname and port
  2478. svr->set_read_timeout (params.timeout_read);
  2479. svr->set_write_timeout(params.timeout_write);
  2480. std::unordered_map<std::string, std::string> log_data;
  2481. log_data["hostname"] = params.hostname;
  2482. log_data["port"] = std::to_string(params.port);
  2483. if (params.api_keys.size() == 1) {
  2484. auto key = params.api_keys[0];
  2485. log_data["api_key"] = "api_key: ****" + key.substr(std::max((int)(key.length() - 4), 0));
  2486. } else if (params.api_keys.size() > 1) {
  2487. log_data["api_key"] = "api_key: " + std::to_string(params.api_keys.size()) + " keys loaded";
  2488. }
  2489. // Necessary similarity of prompt for slot selection
  2490. ctx_server.slot_prompt_similarity = params.slot_prompt_similarity;
  2491. //
  2492. // Middlewares
  2493. //
  2494. auto middleware_validate_api_key = [&params, &res_error](const httplib::Request & req, httplib::Response & res) {
  2495. static const std::unordered_set<std::string> public_endpoints = {
  2496. "/health",
  2497. "/models",
  2498. "/v1/models",
  2499. };
  2500. // If API key is not set, skip validation
  2501. if (params.api_keys.empty()) {
  2502. return true;
  2503. }
  2504. // If path is public or is static file, skip validation
  2505. if (public_endpoints.find(req.path) != public_endpoints.end() || req.path == "/") {
  2506. return true;
  2507. }
  2508. // Check for API key in the header
  2509. auto auth_header = req.get_header_value("Authorization");
  2510. std::string prefix = "Bearer ";
  2511. if (auth_header.substr(0, prefix.size()) == prefix) {
  2512. std::string received_api_key = auth_header.substr(prefix.size());
  2513. if (std::find(params.api_keys.begin(), params.api_keys.end(), received_api_key) != params.api_keys.end()) {
  2514. return true; // API key is valid
  2515. }
  2516. }
  2517. // API key is invalid or not provided
  2518. res_error(res, format_error_response("Invalid API Key", ERROR_TYPE_AUTHENTICATION));
  2519. LOG_WRN("Unauthorized: Invalid API Key\n");
  2520. return false;
  2521. };
  2522. auto middleware_server_state = [&res_error, &state](const httplib::Request & req, httplib::Response & res) {
  2523. server_state current_state = state.load();
  2524. if (current_state == SERVER_STATE_LOADING_MODEL) {
  2525. auto tmp = string_split<std::string>(req.path, '.');
  2526. if (req.path == "/" || tmp.back() == "html") {
  2527. res.set_content(reinterpret_cast<const char*>(loading_html), loading_html_len, "text/html; charset=utf-8");
  2528. res.status = 503;
  2529. } else {
  2530. res_error(res, format_error_response("Loading model", ERROR_TYPE_UNAVAILABLE));
  2531. }
  2532. return false;
  2533. }
  2534. return true;
  2535. };
  2536. // register server middlewares
  2537. svr->set_pre_routing_handler([&middleware_validate_api_key, &middleware_server_state](const httplib::Request & req, httplib::Response & res) {
  2538. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2539. // If this is OPTIONS request, skip validation because browsers don't include Authorization header
  2540. if (req.method == "OPTIONS") {
  2541. res.set_header("Access-Control-Allow-Credentials", "true");
  2542. res.set_header("Access-Control-Allow-Methods", "GET, POST");
  2543. res.set_header("Access-Control-Allow-Headers", "*");
  2544. res.set_content("", "text/html"); // blank response, no data
  2545. return httplib::Server::HandlerResponse::Handled; // skip further processing
  2546. }
  2547. if (!middleware_server_state(req, res)) {
  2548. return httplib::Server::HandlerResponse::Handled;
  2549. }
  2550. if (!middleware_validate_api_key(req, res)) {
  2551. return httplib::Server::HandlerResponse::Handled;
  2552. }
  2553. return httplib::Server::HandlerResponse::Unhandled;
  2554. });
  2555. //
  2556. // Route handlers (or controllers)
  2557. //
  2558. const auto handle_health = [&](const httplib::Request &, httplib::Response & res) {
  2559. // error and loading states are handled by middleware
  2560. json health = {{"status", "ok"}};
  2561. res_ok(res, health);
  2562. };
  2563. const auto handle_slots = [&](const httplib::Request & req, httplib::Response & res) {
  2564. if (!params.endpoint_slots) {
  2565. res_error(res, format_error_response("This server does not support slots endpoint. Start it with `--slots`", ERROR_TYPE_NOT_SUPPORTED));
  2566. return;
  2567. }
  2568. // request slots data using task queue
  2569. server_task task;
  2570. task.id = ctx_server.queue_tasks.get_new_id();
  2571. task.type = SERVER_TASK_TYPE_METRICS;
  2572. ctx_server.queue_results.add_waiting_task_id(task.id);
  2573. ctx_server.queue_tasks.post(task, true); // high-priority task
  2574. // get the result
  2575. server_task_result_ptr result = ctx_server.queue_results.recv(task.id);
  2576. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2577. if (result->is_error()) {
  2578. res_error(res, result->to_json());
  2579. return;
  2580. }
  2581. // TODO: get rid of this dynamic_cast
  2582. auto res_metrics = dynamic_cast<server_task_result_metrics*>(result.get());
  2583. GGML_ASSERT(res_metrics != nullptr);
  2584. // optionally return "fail_on_no_slot" error
  2585. if (req.has_param("fail_on_no_slot")) {
  2586. if (res_metrics->n_idle_slots == 0) {
  2587. res_error(res, format_error_response("no slot available", ERROR_TYPE_UNAVAILABLE));
  2588. return;
  2589. }
  2590. }
  2591. res_ok(res, res_metrics->slots_data);
  2592. };
  2593. const auto handle_metrics = [&](const httplib::Request &, httplib::Response & res) {
  2594. if (!params.endpoint_metrics) {
  2595. res_error(res, format_error_response("This server does not support metrics endpoint. Start it with `--metrics`", ERROR_TYPE_NOT_SUPPORTED));
  2596. return;
  2597. }
  2598. // request slots data using task queue
  2599. server_task task;
  2600. task.id = ctx_server.queue_tasks.get_new_id();
  2601. task.id_target = -1;
  2602. task.type = SERVER_TASK_TYPE_METRICS;
  2603. task.data.push_back({{"reset_bucket", true}});
  2604. ctx_server.queue_results.add_waiting_task_id(task.id);
  2605. ctx_server.queue_tasks.post(task, true); // high-priority task
  2606. // get the result
  2607. server_task_result_ptr result = ctx_server.queue_results.recv(task.id);
  2608. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2609. if (result->is_error()) {
  2610. res_error(res, result->to_json());
  2611. return;
  2612. }
  2613. // TODO: get rid of this dynamic_cast
  2614. auto res_metrics = dynamic_cast<server_task_result_metrics*>(result.get());
  2615. GGML_ASSERT(res_metrics != nullptr);
  2616. // metrics definition: https://prometheus.io/docs/practices/naming/#metric-names
  2617. json all_metrics_def = json {
  2618. {"counter", {{
  2619. {"name", "prompt_tokens_total"},
  2620. {"help", "Number of prompt tokens processed."},
  2621. {"value", (uint64_t) res_metrics->n_prompt_tokens_processed_total}
  2622. }, {
  2623. {"name", "prompt_seconds_total"},
  2624. {"help", "Prompt process time"},
  2625. {"value", (uint64_t) res_metrics->t_prompt_processing_total / 1.e3}
  2626. }, {
  2627. {"name", "tokens_predicted_total"},
  2628. {"help", "Number of generation tokens processed."},
  2629. {"value", (uint64_t) res_metrics->n_tokens_predicted_total}
  2630. }, {
  2631. {"name", "tokens_predicted_seconds_total"},
  2632. {"help", "Predict process time"},
  2633. {"value", (uint64_t) res_metrics->t_tokens_generation_total / 1.e3}
  2634. }, {
  2635. {"name", "n_decode_total"},
  2636. {"help", "Total number of llama_decode() calls"},
  2637. {"value", res_metrics->n_decode_total}
  2638. }, {
  2639. {"name", "n_busy_slots_per_decode"},
  2640. {"help", "Average number of busy slots per llama_decode() call"},
  2641. {"value", (float) res_metrics->n_busy_slots_total / (float) res_metrics->n_decode_total}
  2642. }}},
  2643. {"gauge", {{
  2644. {"name", "prompt_tokens_seconds"},
  2645. {"help", "Average prompt throughput in tokens/s."},
  2646. {"value", res_metrics->n_prompt_tokens_processed ? 1.e3 / res_metrics->t_prompt_processing * res_metrics->n_prompt_tokens_processed : 0.}
  2647. },{
  2648. {"name", "predicted_tokens_seconds"},
  2649. {"help", "Average generation throughput in tokens/s."},
  2650. {"value", res_metrics->n_tokens_predicted ? 1.e3 / res_metrics->t_tokens_generation * res_metrics->n_tokens_predicted : 0.}
  2651. },{
  2652. {"name", "kv_cache_usage_ratio"},
  2653. {"help", "KV-cache usage. 1 means 100 percent usage."},
  2654. {"value", 1. * res_metrics->kv_cache_used_cells / params.n_ctx}
  2655. },{
  2656. {"name", "kv_cache_tokens"},
  2657. {"help", "KV-cache tokens."},
  2658. {"value", (uint64_t) res_metrics->kv_cache_tokens_count}
  2659. },{
  2660. {"name", "requests_processing"},
  2661. {"help", "Number of request processing."},
  2662. {"value", (uint64_t) res_metrics->n_processing_slots}
  2663. },{
  2664. {"name", "requests_deferred"},
  2665. {"help", "Number of request deferred."},
  2666. {"value", (uint64_t) res_metrics->n_tasks_deferred}
  2667. }}}
  2668. };
  2669. std::stringstream prometheus;
  2670. for (const auto & el : all_metrics_def.items()) {
  2671. const auto & type = el.key();
  2672. const auto & metrics_def = el.value();
  2673. for (const auto & metric_def : metrics_def) {
  2674. const std::string name = metric_def.at("name");
  2675. const std::string help = metric_def.at("help");
  2676. auto value = json_value(metric_def, "value", 0.);
  2677. prometheus << "# HELP llamacpp:" << name << " " << help << "\n"
  2678. << "# TYPE llamacpp:" << name << " " << type << "\n"
  2679. << "llamacpp:" << name << " " << value << "\n";
  2680. }
  2681. }
  2682. res.set_header("Process-Start-Time-Unix", std::to_string(res_metrics->t_start));
  2683. res.set_content(prometheus.str(), "text/plain; version=0.0.4");
  2684. res.status = 200; // HTTP OK
  2685. };
  2686. const auto handle_slots_save = [&ctx_server, &res_error, &res_ok, &params](const httplib::Request & req, httplib::Response & res, int id_slot) {
  2687. json request_data = json::parse(req.body);
  2688. std::string filename = request_data.at("filename");
  2689. if (!fs_validate_filename(filename)) {
  2690. res_error(res, format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  2691. return;
  2692. }
  2693. std::string filepath = params.slot_save_path + filename;
  2694. server_task task;
  2695. task.type = SERVER_TASK_TYPE_SLOT_SAVE;
  2696. task.data = {
  2697. { "id_slot", id_slot },
  2698. { "filename", filename },
  2699. { "filepath", filepath },
  2700. };
  2701. const int id_task = ctx_server.queue_tasks.post(task);
  2702. ctx_server.queue_results.add_waiting_task_id(id_task);
  2703. server_task_result_ptr result = ctx_server.queue_results.recv(id_task);
  2704. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2705. if (result->is_error()) {
  2706. res_error(res, result->to_json());
  2707. return;
  2708. }
  2709. res_ok(res, result->to_json());
  2710. };
  2711. const auto handle_slots_restore = [&ctx_server, &res_error, &res_ok, &params](const httplib::Request & req, httplib::Response & res, int id_slot) {
  2712. json request_data = json::parse(req.body);
  2713. std::string filename = request_data.at("filename");
  2714. if (!fs_validate_filename(filename)) {
  2715. res_error(res, format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  2716. return;
  2717. }
  2718. std::string filepath = params.slot_save_path + filename;
  2719. server_task task;
  2720. task.type = SERVER_TASK_TYPE_SLOT_RESTORE;
  2721. task.data = {
  2722. { "id_slot", id_slot },
  2723. { "filename", filename },
  2724. { "filepath", filepath },
  2725. };
  2726. const int id_task = ctx_server.queue_tasks.post(task);
  2727. ctx_server.queue_results.add_waiting_task_id(id_task);
  2728. server_task_result_ptr result = ctx_server.queue_results.recv(id_task);
  2729. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2730. if (result->is_error()) {
  2731. res_error(res, result->to_json());
  2732. return;
  2733. }
  2734. GGML_ASSERT(dynamic_cast<server_task_result_slot_save_load*>(result.get()) != nullptr);
  2735. res_ok(res, result->to_json());
  2736. };
  2737. const auto handle_slots_erase = [&ctx_server, &res_error, &res_ok](const httplib::Request & /* req */, httplib::Response & res, int id_slot) {
  2738. server_task task;
  2739. task.type = SERVER_TASK_TYPE_SLOT_ERASE;
  2740. task.data = {
  2741. { "id_slot", id_slot },
  2742. };
  2743. const int id_task = ctx_server.queue_tasks.post(task);
  2744. ctx_server.queue_results.add_waiting_task_id(id_task);
  2745. server_task_result_ptr result = ctx_server.queue_results.recv(id_task);
  2746. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2747. if (result->is_error()) {
  2748. res_error(res, result->to_json());
  2749. return;
  2750. }
  2751. GGML_ASSERT(dynamic_cast<server_task_result_slot_erase*>(result.get()) != nullptr);
  2752. res_ok(res, result->to_json());
  2753. };
  2754. const auto handle_slots_action = [&params, &res_error, &handle_slots_save, &handle_slots_restore, &handle_slots_erase](const httplib::Request & req, httplib::Response & res) {
  2755. if (params.slot_save_path.empty()) {
  2756. res_error(res, format_error_response("This server does not support slots action. Start it with `--slot-save-path`", ERROR_TYPE_NOT_SUPPORTED));
  2757. return;
  2758. }
  2759. std::string id_slot_str = req.path_params.at("id_slot");
  2760. int id_slot;
  2761. try {
  2762. id_slot = std::stoi(id_slot_str);
  2763. } catch (const std::exception &) {
  2764. res_error(res, format_error_response("Invalid slot ID", ERROR_TYPE_INVALID_REQUEST));
  2765. return;
  2766. }
  2767. std::string action = req.get_param_value("action");
  2768. if (action == "save") {
  2769. handle_slots_save(req, res, id_slot);
  2770. } else if (action == "restore") {
  2771. handle_slots_restore(req, res, id_slot);
  2772. } else if (action == "erase") {
  2773. handle_slots_erase(req, res, id_slot);
  2774. } else {
  2775. res_error(res, format_error_response("Invalid action", ERROR_TYPE_INVALID_REQUEST));
  2776. }
  2777. };
  2778. const auto handle_props = [&ctx_server, &res_ok](const httplib::Request &, httplib::Response & res) {
  2779. json data = {
  2780. { "default_generation_settings", ctx_server.default_generation_settings_for_props },
  2781. { "total_slots", ctx_server.params_base.n_parallel },
  2782. { "chat_template", llama_get_chat_template(ctx_server.model) },
  2783. };
  2784. res_ok(res, data);
  2785. };
  2786. const auto handle_props_change = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2787. if (!ctx_server.params_base.endpoint_props) {
  2788. res_error(res, format_error_response("This server does not support changing global properties. Start it with `--props`", ERROR_TYPE_NOT_SUPPORTED));
  2789. return;
  2790. }
  2791. json data = json::parse(req.body);
  2792. // update any props here
  2793. res_ok(res, {{ "success", true }});
  2794. };
  2795. // handle completion-like requests (completion, chat, infill)
  2796. // we can optionally provide a custom format for partial results and final results
  2797. const auto handle_completions_generic = [&ctx_server, &res_error, &res_ok](
  2798. server_task_inf_type inf_type,
  2799. json & data,
  2800. httplib::Response & res,
  2801. bool oai_compat = false) {
  2802. if (ctx_server.params_base.embedding) {
  2803. res_error(res, format_error_response("This server does not support completions. Start it without `--embeddings`", ERROR_TYPE_NOT_SUPPORTED));
  2804. return;
  2805. }
  2806. data["completion_id"] = gen_chatcmplid();
  2807. std::vector<server_task> tasks = ctx_server.create_tasks_inference(data, inf_type);
  2808. ctx_server.queue_results.add_waiting_tasks(tasks);
  2809. ctx_server.queue_tasks.post(tasks);
  2810. bool stream = json_value(data, "stream", false);
  2811. const auto task_ids = server_task::get_list_id(tasks);
  2812. if (!stream) {
  2813. ctx_server.receive_multi_results(task_ids, [&](std::vector<server_task_result_ptr> & results) {
  2814. if (results.size() == 1) {
  2815. // single result
  2816. res_ok(res, results[0]->to_json());
  2817. } else {
  2818. // multiple results (multitask)
  2819. json arr = json::array();
  2820. for (auto & res : results) {
  2821. arr.push_back(res->to_json());
  2822. }
  2823. res_ok(res, arr);
  2824. }
  2825. }, [&](const json & error_data) {
  2826. res_error(res, error_data);
  2827. });
  2828. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  2829. } else {
  2830. const auto chunked_content_provider = [task_ids, &ctx_server, oai_compat](size_t, httplib::DataSink & sink) {
  2831. ctx_server.receive_cmpl_results_stream(task_ids, [&](server_task_result_ptr & result) -> bool {
  2832. json res_json = result->to_json();
  2833. if (res_json.is_array()) {
  2834. for (const auto & res : res_json) {
  2835. if (!server_sent_event(sink, "data", res)) {
  2836. return false;
  2837. }
  2838. }
  2839. return true;
  2840. } else {
  2841. return server_sent_event(sink, "data", res_json);
  2842. }
  2843. }, [&](const json & error_data) {
  2844. server_sent_event(sink, "error", error_data);
  2845. });
  2846. if (oai_compat) {
  2847. static const std::string ev_done = "data: [DONE]\n\n";
  2848. sink.write(ev_done.data(), ev_done.size());
  2849. }
  2850. sink.done();
  2851. return false;
  2852. };
  2853. auto on_complete = [task_ids, &ctx_server] (bool) {
  2854. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  2855. };
  2856. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2857. }
  2858. };
  2859. const auto handle_completions = [&handle_completions_generic](const httplib::Request & req, httplib::Response & res) {
  2860. json data = json::parse(req.body);
  2861. return handle_completions_generic(SERVER_TASK_INF_TYPE_COMPLETION, data, res);
  2862. };
  2863. const auto handle_infill = [&ctx_server, &res_error, &handle_completions_generic](const httplib::Request & req, httplib::Response & res) {
  2864. // check model compatibility
  2865. std::string err;
  2866. if (llama_token_fim_pre(ctx_server.model) == LLAMA_TOKEN_NULL) {
  2867. err += "prefix token is missing. ";
  2868. }
  2869. if (llama_token_fim_suf(ctx_server.model) == LLAMA_TOKEN_NULL) {
  2870. err += "suffix token is missing. ";
  2871. }
  2872. if (llama_token_fim_mid(ctx_server.model) == LLAMA_TOKEN_NULL) {
  2873. err += "middle token is missing. ";
  2874. }
  2875. if (!err.empty()) {
  2876. res_error(res, format_error_response(string_format("Infill is not supported by this model: %s", err.c_str()), ERROR_TYPE_NOT_SUPPORTED));
  2877. return;
  2878. }
  2879. json data = json::parse(req.body);
  2880. // validate input
  2881. if (!data.contains("input_prefix")) {
  2882. res_error(res, format_error_response("\"input_prefix\" is required", ERROR_TYPE_INVALID_REQUEST));
  2883. }
  2884. if (!data.contains("input_suffix")) {
  2885. res_error(res, format_error_response("\"input_suffix\" is required", ERROR_TYPE_INVALID_REQUEST));
  2886. }
  2887. if (data.contains("input_extra") && !data.at("input_extra").is_array()) {
  2888. res_error(res, format_error_response("\"input_extra\" must be an array of {\"filename\": string, \"text\": string}", ERROR_TYPE_INVALID_REQUEST));
  2889. return;
  2890. }
  2891. json input_extra = json_value(data, "input_extra", json::array());
  2892. for (const auto & chunk : input_extra) {
  2893. // { "text": string, "filename": string }
  2894. if (!chunk.contains("text") || !chunk.at("text").is_string()) {
  2895. res_error(res, format_error_response("extra_context chunk must contain a \"text\" field with a string value", ERROR_TYPE_INVALID_REQUEST));
  2896. return;
  2897. }
  2898. // filename is optional
  2899. if (chunk.contains("filename") && !chunk.at("filename").is_string()) {
  2900. res_error(res, format_error_response("extra_context chunk's \"filename\" field must be a string", ERROR_TYPE_INVALID_REQUEST));
  2901. return;
  2902. }
  2903. }
  2904. data["input_extra"] = input_extra; // default to empty array if it's not exist
  2905. return handle_completions_generic(SERVER_TASK_INF_TYPE_INFILL, data, res);
  2906. };
  2907. const auto handle_chat_completions = [&ctx_server, &params, &res_error, &handle_completions_generic](const httplib::Request & req, httplib::Response & res) {
  2908. if (ctx_server.params_base.embedding) {
  2909. res_error(res, format_error_response("This server does not support completions. Start it without `--embeddings`", ERROR_TYPE_NOT_SUPPORTED));
  2910. return;
  2911. }
  2912. json data = oaicompat_completion_params_parse(ctx_server.model, json::parse(req.body), params.chat_template);
  2913. data["__oaicompat_chat"] = true;
  2914. return handle_completions_generic(SERVER_TASK_INF_TYPE_COMPLETION, data, res, true);
  2915. };
  2916. const auto handle_models = [&params, &ctx_server](const httplib::Request &, httplib::Response & res) {
  2917. json models = {
  2918. {"object", "list"},
  2919. {"data", {
  2920. {
  2921. {"id", params.model_alias},
  2922. {"object", "model"},
  2923. {"created", std::time(0)},
  2924. {"owned_by", "llamacpp"},
  2925. {"meta", ctx_server.model_meta()}
  2926. },
  2927. }}
  2928. };
  2929. res.set_content(models.dump(), MIMETYPE_JSON);
  2930. };
  2931. const auto handle_tokenize = [&ctx_server, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2932. const json body = json::parse(req.body);
  2933. json tokens_response = json::array();
  2934. if (body.count("content") != 0) {
  2935. const bool add_special = json_value(body, "add_special", false);
  2936. const bool with_pieces = json_value(body, "with_pieces", false);
  2937. llama_tokens tokens = tokenize_mixed(ctx_server.ctx, body.at("content"), add_special, true);
  2938. if (with_pieces) {
  2939. for (const auto& token : tokens) {
  2940. std::string piece = common_token_to_piece(ctx_server.ctx, token);
  2941. json piece_json;
  2942. // Check if the piece is valid UTF-8
  2943. if (is_valid_utf8(piece)) {
  2944. piece_json = piece;
  2945. } else {
  2946. // If not valid UTF-8, store as array of byte values
  2947. piece_json = json::array();
  2948. for (unsigned char c : piece) {
  2949. piece_json.push_back(static_cast<int>(c));
  2950. }
  2951. }
  2952. tokens_response.push_back({
  2953. {"id", token},
  2954. {"piece", piece_json}
  2955. });
  2956. }
  2957. } else {
  2958. tokens_response = tokens;
  2959. }
  2960. }
  2961. const json data = format_tokenizer_response(tokens_response);
  2962. res_ok(res, data);
  2963. };
  2964. const auto handle_detokenize = [&ctx_server, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2965. const json body = json::parse(req.body);
  2966. std::string content;
  2967. if (body.count("tokens") != 0) {
  2968. const llama_tokens tokens = body.at("tokens");
  2969. content = tokens_to_str(ctx_server.ctx, tokens.cbegin(), tokens.cend());
  2970. }
  2971. const json data = format_detokenized_response(content);
  2972. res_ok(res, data);
  2973. };
  2974. const auto handle_embeddings = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2975. const json body = json::parse(req.body);
  2976. bool oaicompat = false;
  2977. // an input prompt can be a string or a list of tokens (integer)
  2978. json prompt;
  2979. if (body.count("input") != 0) {
  2980. oaicompat = true;
  2981. prompt = body.at("input");
  2982. } else if (body.count("content") != 0) {
  2983. // with "content", we only support single prompt
  2984. prompt = std::vector<std::string>{body.at("content")};
  2985. } else {
  2986. res_error(res, format_error_response("\"input\" or \"content\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  2987. return;
  2988. }
  2989. // create and queue the task
  2990. json responses = json::array();
  2991. bool error = false;
  2992. {
  2993. std::vector<server_task> tasks = ctx_server.create_tasks_inference({{"prompt", prompt}}, SERVER_TASK_INF_TYPE_EMBEDDING);
  2994. ctx_server.queue_results.add_waiting_tasks(tasks);
  2995. ctx_server.queue_tasks.post(tasks);
  2996. // get the result
  2997. std::unordered_set<int> task_ids = server_task::get_list_id(tasks);
  2998. ctx_server.receive_multi_results(task_ids, [&](std::vector<server_task_result_ptr> & results) {
  2999. for (auto & res : results) {
  3000. GGML_ASSERT(dynamic_cast<server_task_result_embd*>(res.get()) != nullptr);
  3001. responses.push_back(res->to_json());
  3002. }
  3003. }, [&](const json & error_data) {
  3004. res_error(res, error_data);
  3005. error = true;
  3006. });
  3007. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  3008. }
  3009. if (error) {
  3010. return;
  3011. }
  3012. // write JSON response
  3013. json root = oaicompat
  3014. ? format_embeddings_response_oaicompat(body, responses)
  3015. : responses[0];
  3016. res_ok(res, root);
  3017. };
  3018. const auto handle_rerank = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  3019. if (!ctx_server.params_base.reranking || ctx_server.params_base.embedding) {
  3020. res_error(res, format_error_response("This server does not support reranking. Start it with `--reranking` and without `--embedding`", ERROR_TYPE_NOT_SUPPORTED));
  3021. return;
  3022. }
  3023. const json body = json::parse(req.body);
  3024. // TODO: implement
  3025. //int top_n = 1;
  3026. //if (body.count("top_n") != 1) {
  3027. // top_n = body.at("top_n");
  3028. //} else {
  3029. // res_error(res, format_error_response("\"top_n\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  3030. // return;
  3031. //}
  3032. json query;
  3033. if (body.count("query") == 1) {
  3034. query = body.at("query");
  3035. if (!query.is_string()) {
  3036. res_error(res, format_error_response("\"query\" must be a string", ERROR_TYPE_INVALID_REQUEST));
  3037. return;
  3038. }
  3039. } else {
  3040. res_error(res, format_error_response("\"query\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  3041. return;
  3042. }
  3043. std::vector<std::string> documents = json_value(body, "documents", std::vector<std::string>());
  3044. if (documents.empty()) {
  3045. res_error(res, format_error_response("\"documents\" must be a non-empty string array", ERROR_TYPE_INVALID_REQUEST));
  3046. return;
  3047. }
  3048. // construct prompt object: array of ["query", "doc0", "doc1", ...]
  3049. json prompt;
  3050. prompt.push_back(query);
  3051. for (const auto & doc : documents) {
  3052. prompt.push_back(doc);
  3053. }
  3054. LOG_DBG("rerank prompt: %s\n", prompt.dump().c_str());
  3055. // create and queue the task
  3056. json responses = json::array();
  3057. bool error = false;
  3058. {
  3059. std::vector<server_task> tasks = ctx_server.create_tasks_inference({{"prompt", prompt}}, SERVER_TASK_INF_TYPE_RERANK);
  3060. ctx_server.queue_results.add_waiting_tasks(tasks);
  3061. ctx_server.queue_tasks.post(tasks);
  3062. // get the result
  3063. std::unordered_set<int> task_ids = server_task::get_list_id(tasks);
  3064. ctx_server.receive_multi_results(task_ids, [&](std::vector<server_task_result_ptr> & results) {
  3065. for (auto & res : results) {
  3066. GGML_ASSERT(dynamic_cast<server_task_result_rerank*>(res.get()) != nullptr);
  3067. responses.push_back(res->to_json());
  3068. }
  3069. }, [&](const json & error_data) {
  3070. res_error(res, error_data);
  3071. error = true;
  3072. });
  3073. }
  3074. if (error) {
  3075. return;
  3076. }
  3077. // write JSON response
  3078. json root = format_response_rerank(body, responses);
  3079. res_ok(res, root);
  3080. };
  3081. const auto handle_lora_adapters_list = [&](const httplib::Request &, httplib::Response & res) {
  3082. json result = json::array();
  3083. for (size_t i = 0; i < ctx_server.loras.size(); ++i) {
  3084. auto & lora = ctx_server.loras[i];
  3085. result.push_back({
  3086. {"id", i},
  3087. {"path", lora.path},
  3088. {"scale", lora.scale},
  3089. });
  3090. }
  3091. res_ok(res, result);
  3092. res.status = 200; // HTTP OK
  3093. };
  3094. const auto handle_lora_adapters_apply = [&](const httplib::Request & req, httplib::Response & res) {
  3095. const std::vector<json> body = json::parse(req.body);
  3096. int max_idx = ctx_server.loras.size();
  3097. // clear existing value
  3098. for (auto & lora : ctx_server.loras) {
  3099. lora.scale = 0.0f;
  3100. }
  3101. // set value
  3102. for (auto entry : body) {
  3103. int id = entry.at("id");
  3104. float scale = entry.at("scale");
  3105. if (0 <= id && id < max_idx) {
  3106. ctx_server.loras[id].scale = scale;
  3107. } else {
  3108. throw std::runtime_error("invalid adapter id");
  3109. }
  3110. }
  3111. server_task task;
  3112. task.type = SERVER_TASK_TYPE_SET_LORA;
  3113. const int id_task = ctx_server.queue_tasks.post(task);
  3114. ctx_server.queue_results.add_waiting_task_id(id_task);
  3115. server_task_result_ptr result = ctx_server.queue_results.recv(id_task);
  3116. ctx_server.queue_results.remove_waiting_task_id(id_task);
  3117. if (result->is_error()) {
  3118. res_error(res, result->to_json());
  3119. return;
  3120. }
  3121. GGML_ASSERT(dynamic_cast<server_task_result_apply_lora*>(result.get()) != nullptr);
  3122. res_ok(res, result->to_json());
  3123. };
  3124. //
  3125. // Router
  3126. //
  3127. // register static assets routes
  3128. if (!params.public_path.empty()) {
  3129. // Set the base directory for serving static files
  3130. bool is_found = svr->set_mount_point("/", params.public_path);
  3131. if (!is_found) {
  3132. LOG_ERR("%s: static assets path not found: %s\n", __func__, params.public_path.c_str());
  3133. return 1;
  3134. }
  3135. } else {
  3136. // using embedded static index.html
  3137. svr->Get("/", [](const httplib::Request &, httplib::Response & res) {
  3138. res.set_content(reinterpret_cast<const char*>(index_html), index_html_len, "text/html; charset=utf-8");
  3139. return false;
  3140. });
  3141. }
  3142. // register API routes
  3143. svr->Get ("/health", handle_health); // public endpoint (no API key check)
  3144. svr->Get ("/metrics", handle_metrics);
  3145. svr->Get ("/props", handle_props);
  3146. svr->Post("/props", handle_props_change);
  3147. svr->Get ("/models", handle_models); // public endpoint (no API key check)
  3148. svr->Get ("/v1/models", handle_models); // public endpoint (no API key check)
  3149. svr->Post("/completion", handle_completions); // legacy
  3150. svr->Post("/completions", handle_completions);
  3151. svr->Post("/v1/completions", handle_completions);
  3152. svr->Post("/chat/completions", handle_chat_completions);
  3153. svr->Post("/v1/chat/completions", handle_chat_completions);
  3154. svr->Post("/infill", handle_infill);
  3155. svr->Post("/embedding", handle_embeddings); // legacy
  3156. svr->Post("/embeddings", handle_embeddings);
  3157. svr->Post("/v1/embeddings", handle_embeddings);
  3158. svr->Post("/rerank", handle_rerank);
  3159. svr->Post("/reranking", handle_rerank);
  3160. svr->Post("/v1/rerank", handle_rerank);
  3161. svr->Post("/v1/reranking", handle_rerank);
  3162. svr->Post("/tokenize", handle_tokenize);
  3163. svr->Post("/detokenize", handle_detokenize);
  3164. // LoRA adapters hotswap
  3165. svr->Get ("/lora-adapters", handle_lora_adapters_list);
  3166. svr->Post("/lora-adapters", handle_lora_adapters_apply);
  3167. // Save & load slots
  3168. svr->Get ("/slots", handle_slots);
  3169. svr->Post("/slots/:id_slot", handle_slots_action);
  3170. //
  3171. // Start the server
  3172. //
  3173. if (params.n_threads_http < 1) {
  3174. // +2 threads for monitoring endpoints
  3175. params.n_threads_http = std::max(params.n_parallel + 2, (int32_t) std::thread::hardware_concurrency() - 1);
  3176. }
  3177. log_data["n_threads_http"] = std::to_string(params.n_threads_http);
  3178. svr->new_task_queue = [&params] { return new httplib::ThreadPool(params.n_threads_http); };
  3179. // clean up function, to be called before exit
  3180. auto clean_up = [&svr]() {
  3181. svr->stop();
  3182. llama_backend_free();
  3183. };
  3184. // bind HTTP listen port
  3185. bool was_bound = false;
  3186. if (params.port == 0) {
  3187. int bound_port = svr->bind_to_any_port(params.hostname);
  3188. if ((was_bound = (bound_port >= 0))) {
  3189. params.port = bound_port;
  3190. }
  3191. } else {
  3192. was_bound = svr->bind_to_port(params.hostname, params.port);
  3193. }
  3194. if (!was_bound) {
  3195. //LOG_ERROR("couldn't bind HTTP server socket", {
  3196. // {"hostname", params.hostname},
  3197. // {"port", params.port},
  3198. //});
  3199. LOG_ERR("%s: couldn't bind HTTP server socket, hostname: %s, port: %d\n", __func__, params.hostname.c_str(), params.port);
  3200. clean_up();
  3201. return 1;
  3202. }
  3203. // run the HTTP server in a thread
  3204. std::thread t([&]() { svr->listen_after_bind(); });
  3205. svr->wait_until_ready();
  3206. 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);
  3207. // load the model
  3208. LOG_INF("%s: loading model\n", __func__);
  3209. if (!ctx_server.load_model(params)) {
  3210. clean_up();
  3211. t.join();
  3212. LOG_ERR("%s: exiting due to model loading error\n", __func__);
  3213. return 1;
  3214. }
  3215. ctx_server.init();
  3216. state.store(SERVER_STATE_READY);
  3217. LOG_INF("%s: model loaded\n", __func__);
  3218. // if a custom chat template is not supplied, we will use the one that comes with the model (if any)
  3219. if (params.chat_template.empty()) {
  3220. if (!ctx_server.validate_model_chat_template()) {
  3221. LOG_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__);
  3222. params.chat_template = "chatml";
  3223. }
  3224. }
  3225. // print sample chat example to make it clear which template is used
  3226. LOG_INF("%s: chat template, built_in: %d, chat_example: '%s'\n", __func__, params.chat_template.empty(), common_chat_format_example(ctx_server.model, params.chat_template).c_str());
  3227. ctx_server.queue_tasks.on_new_task(std::bind(
  3228. &server_context::process_single_task, &ctx_server, std::placeholders::_1));
  3229. ctx_server.queue_tasks.on_update_slots(std::bind(
  3230. &server_context::update_slots, &ctx_server));
  3231. shutdown_handler = [&](int) {
  3232. ctx_server.queue_tasks.terminate();
  3233. };
  3234. LOG_INF("%s: server is listening on http://%s:%d - starting the main loop\n", __func__, params.hostname.c_str(), params.port);
  3235. ctx_server.queue_tasks.start_loop();
  3236. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  3237. struct sigaction sigint_action;
  3238. sigint_action.sa_handler = signal_handler;
  3239. sigemptyset (&sigint_action.sa_mask);
  3240. sigint_action.sa_flags = 0;
  3241. sigaction(SIGINT, &sigint_action, NULL);
  3242. sigaction(SIGTERM, &sigint_action, NULL);
  3243. #elif defined (_WIN32)
  3244. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  3245. return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
  3246. };
  3247. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  3248. #endif
  3249. clean_up();
  3250. t.join();
  3251. return 0;
  3252. }