server.cpp 140 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523
  1. #include "utils.hpp"
  2. #include "common.h"
  3. #include "llama.h"
  4. #include "grammar-parser.h"
  5. #ifndef NDEBUG
  6. // crash the server in debug mode, otherwise send an http 500 error
  7. #define CPPHTTPLIB_NO_EXCEPTIONS 1
  8. #endif
  9. // increase max payload length to allow use of larger context size
  10. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 1048576
  11. #include "httplib.h"
  12. #include "json.hpp"
  13. // auto generated files (update with ./deps.sh)
  14. #include "index.html.hpp"
  15. #include "index.js.hpp"
  16. #include "completion.js.hpp"
  17. #include "json-schema-to-grammar.mjs.hpp"
  18. #include <atomic>
  19. #include <chrono>
  20. #include <condition_variable>
  21. #include <cstddef>
  22. #include <set>
  23. #include <mutex>
  24. #include <thread>
  25. #include <signal.h>
  26. #include <memory>
  27. using json = nlohmann::json;
  28. bool server_verbose = false;
  29. bool server_log_json = true;
  30. enum stop_type {
  31. STOP_TYPE_FULL,
  32. STOP_TYPE_PARTIAL,
  33. };
  34. enum slot_state {
  35. SLOT_STATE_IDLE,
  36. SLOT_STATE_PROCESSING,
  37. };
  38. enum slot_command {
  39. SLOT_COMMAND_NONE,
  40. SLOT_COMMAND_LOAD_PROMPT,
  41. SLOT_COMMAND_RELEASE,
  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. SERVER_STATE_ERROR // An error occurred, load_model failed
  47. };
  48. enum server_task_type {
  49. SERVER_TASK_TYPE_COMPLETION,
  50. SERVER_TASK_TYPE_CANCEL,
  51. SERVER_TASK_TYPE_NEXT_RESPONSE,
  52. SERVER_TASK_TYPE_METRICS
  53. };
  54. struct server_task {
  55. int id = -1; // to be filled by server_queue
  56. int id_multi = -1;
  57. int id_target = -1;
  58. server_task_type type;
  59. json data;
  60. bool infill = false;
  61. bool embedding = false;
  62. };
  63. struct server_task_result {
  64. int id = -1;
  65. int id_multi = -1;
  66. json data;
  67. bool stop;
  68. bool error;
  69. };
  70. struct server_task_multi {
  71. int id = -1;
  72. std::set<int> subtasks_remaining;
  73. std::vector<server_task_result> results;
  74. };
  75. struct slot_params {
  76. bool stream = true;
  77. bool cache_prompt = false; // remember the prompt to avoid reprocessing all prompt
  78. uint32_t seed = -1; // RNG seed
  79. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  80. int32_t n_predict = -1; // new tokens to predict
  81. std::vector<std::string> antiprompt;
  82. json input_prefix;
  83. json input_suffix;
  84. };
  85. struct server_params {
  86. int32_t port = 8080;
  87. int32_t read_timeout = 600;
  88. int32_t write_timeout = 600;
  89. int32_t n_threads_http = -1;
  90. std::string hostname = "127.0.0.1";
  91. std::string public_path = "";
  92. std::string chat_template = "";
  93. std::string system_prompt = "";
  94. std::vector<std::string> api_keys;
  95. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  96. std::string ssl_key_file = "";
  97. std::string ssl_cert_file = "";
  98. #endif
  99. bool slots_endpoint = true;
  100. bool metrics_endpoint = false;
  101. };
  102. struct server_slot {
  103. int id;
  104. int id_task = -1;
  105. int id_multi = -1;
  106. struct slot_params params;
  107. slot_state state = SLOT_STATE_IDLE;
  108. slot_command command = SLOT_COMMAND_NONE;
  109. // used to determine the slot that has been used the longest
  110. int64_t t_last_used = -1;
  111. // generation props
  112. int32_t n_ctx = 0; // context size per slot
  113. int32_t n_past = 0;
  114. int32_t n_decoded = 0;
  115. int32_t n_remaining = -1;
  116. int32_t i_batch = -1;
  117. int32_t n_predict = -1;
  118. int32_t n_prompt_tokens = 0;
  119. int32_t n_prompt_tokens_processed = 0;
  120. json prompt;
  121. // when a task is submitted, we first tokenize the prompt and store it here
  122. std::vector<llama_token> prompt_tokens;
  123. std::string generated_text;
  124. std::vector<llama_token> cache_tokens;
  125. std::vector<completion_token_output> generated_token_probs;
  126. bool infill = false;
  127. bool embedding = false;
  128. bool has_next_token = true;
  129. bool truncated = false;
  130. bool stopped_eos = false;
  131. bool stopped_word = false;
  132. bool stopped_limit = false;
  133. bool oaicompat = false;
  134. std::string oaicompat_model;
  135. std::string stopping_word;
  136. // sampling
  137. llama_token sampled;
  138. struct llama_sampling_params sparams;
  139. llama_sampling_context * ctx_sampling = nullptr;
  140. int32_t ga_i = 0; // group-attention state
  141. int32_t ga_n = 1; // group-attention factor
  142. int32_t ga_w = 512; // group-attention width
  143. int32_t n_past_se = 0; // self-extend
  144. // stats
  145. size_t n_sent_text = 0; // number of sent text character
  146. size_t n_sent_token_probs = 0;
  147. int64_t t_start_process_prompt;
  148. int64_t t_start_generation;
  149. double t_prompt_processing; // ms
  150. double t_token_generation; // ms
  151. void reset() {
  152. n_prompt_tokens = 0;
  153. generated_text = "";
  154. truncated = false;
  155. stopped_eos = false;
  156. stopped_word = false;
  157. stopped_limit = false;
  158. stopping_word = "";
  159. n_past = 0;
  160. n_sent_text = 0;
  161. n_sent_token_probs = 0;
  162. infill = false;
  163. ga_i = 0;
  164. n_past_se = 0;
  165. generated_token_probs.clear();
  166. }
  167. bool has_budget(gpt_params &global_params) {
  168. if (params.n_predict == -1 && global_params.n_predict == -1) {
  169. return true; // limitless
  170. }
  171. n_remaining = -1;
  172. if (params.n_predict != -1) {
  173. n_remaining = params.n_predict - n_decoded;
  174. } else if (global_params.n_predict != -1) {
  175. n_remaining = global_params.n_predict - n_decoded;
  176. }
  177. return n_remaining > 0; // no budget
  178. }
  179. bool available() const {
  180. return state == SLOT_STATE_IDLE && command == SLOT_COMMAND_NONE;
  181. }
  182. bool is_processing() const {
  183. return (state == SLOT_STATE_IDLE && command == SLOT_COMMAND_LOAD_PROMPT) || state == SLOT_STATE_PROCESSING;
  184. }
  185. void add_token_string(const completion_token_output & token) {
  186. if (command == SLOT_COMMAND_RELEASE) {
  187. return;
  188. }
  189. generated_token_probs.push_back(token);
  190. }
  191. void release() {
  192. if (state == SLOT_STATE_PROCESSING) {
  193. t_token_generation = (ggml_time_us() - t_start_generation) / 1e3;
  194. command = SLOT_COMMAND_RELEASE;
  195. }
  196. }
  197. json get_formated_timings() const {
  198. return json {
  199. {"prompt_n", n_prompt_tokens_processed},
  200. {"prompt_ms", t_prompt_processing},
  201. {"prompt_per_token_ms", t_prompt_processing / n_prompt_tokens_processed},
  202. {"prompt_per_second", 1e3 / t_prompt_processing * n_prompt_tokens_processed},
  203. {"predicted_n", n_decoded},
  204. {"predicted_ms", t_token_generation},
  205. {"predicted_per_token_ms", t_token_generation / n_decoded},
  206. {"predicted_per_second", 1e3 / t_token_generation * n_decoded},
  207. };
  208. }
  209. size_t find_stopping_strings(const std::string & text, const size_t last_token_size, const stop_type type) {
  210. size_t stop_pos = std::string::npos;
  211. for (const std::string & word : params.antiprompt) {
  212. size_t pos;
  213. if (type == STOP_TYPE_FULL) {
  214. const size_t tmp = word.size() + last_token_size;
  215. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  216. pos = text.find(word, from_pos);
  217. } else {
  218. pos = find_partial_stop_string(word, text);
  219. }
  220. if (pos != std::string::npos && (stop_pos == std::string::npos || pos < stop_pos)) {
  221. if (type == STOP_TYPE_FULL) {
  222. stopped_word = true;
  223. stopping_word = word;
  224. has_next_token = false;
  225. }
  226. stop_pos = pos;
  227. }
  228. }
  229. return stop_pos;
  230. }
  231. void print_timings() const {
  232. char buffer[512];
  233. double t_token = t_prompt_processing / n_prompt_tokens_processed;
  234. double n_tokens_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  235. snprintf(buffer, 512, "prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)",
  236. t_prompt_processing, n_prompt_tokens_processed,
  237. t_token, n_tokens_second);
  238. LOG_INFO(buffer, {
  239. {"id_slot", id},
  240. {"id_task", id_task},
  241. {"t_prompt_processing", t_prompt_processing},
  242. {"n_prompt_tokens_processed", n_prompt_tokens_processed},
  243. {"t_token", t_token},
  244. {"n_tokens_second", n_tokens_second},
  245. });
  246. t_token = t_token_generation / n_decoded;
  247. n_tokens_second = 1e3 / t_token_generation * n_decoded;
  248. snprintf(buffer, 512, "generation eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)",
  249. t_token_generation, n_decoded,
  250. t_token, n_tokens_second);
  251. LOG_INFO(buffer, {
  252. {"id_slot", id},
  253. {"id_task", id_task},
  254. {"t_token_generation", t_token_generation},
  255. {"n_decoded", n_decoded},
  256. {"t_token", t_token},
  257. {"n_tokens_second", n_tokens_second},
  258. });
  259. snprintf(buffer, 512, " total time = %10.2f ms", t_prompt_processing + t_token_generation);
  260. LOG_INFO(buffer, {
  261. {"id_slot", id},
  262. {"id_task", id_task},
  263. {"t_prompt_processing", t_prompt_processing},
  264. {"t_token_generation", t_token_generation},
  265. {"t_total", t_prompt_processing + t_token_generation},
  266. });
  267. }
  268. };
  269. struct server_metrics {
  270. int64_t t_start = 0;
  271. uint64_t n_prompt_tokens_processed_total = 0;
  272. uint64_t t_prompt_processing_total = 0;
  273. uint64_t n_tokens_predicted_total = 0;
  274. uint64_t t_tokens_generation_total = 0;
  275. uint64_t n_prompt_tokens_processed = 0;
  276. uint64_t t_prompt_processing = 0;
  277. uint64_t n_tokens_predicted = 0;
  278. uint64_t t_tokens_generation = 0;
  279. void init() {
  280. t_start = ggml_time_us();
  281. }
  282. void on_prompt_eval(const server_slot & slot) {
  283. n_prompt_tokens_processed_total += slot.n_prompt_tokens_processed;
  284. n_prompt_tokens_processed += slot.n_prompt_tokens_processed;
  285. t_prompt_processing += slot.t_prompt_processing;
  286. t_prompt_processing_total += slot.t_prompt_processing;
  287. }
  288. void on_prediction(const server_slot & slot) {
  289. n_tokens_predicted_total += slot.n_decoded;
  290. n_tokens_predicted += slot.n_decoded;
  291. t_tokens_generation += slot.t_token_generation;
  292. t_tokens_generation_total += slot.t_token_generation;
  293. }
  294. void reset_bucket() {
  295. n_prompt_tokens_processed = 0;
  296. t_prompt_processing = 0;
  297. n_tokens_predicted = 0;
  298. t_tokens_generation = 0;
  299. }
  300. };
  301. struct server_queue {
  302. int id = 0;
  303. bool running;
  304. // queues
  305. std::vector<server_task> queue_tasks;
  306. std::vector<server_task> queue_tasks_deferred;
  307. std::vector<server_task_multi> queue_multitasks;
  308. std::mutex mutex_tasks;
  309. std::condition_variable condition_tasks;
  310. // callback functions
  311. std::function<void(server_task &)> callback_new_task;
  312. std::function<void(server_task_multi &)> callback_finish_multitask;
  313. std::function<void(void)> callback_update_slots;
  314. // Add a new task to the end of the queue
  315. int post(server_task task) {
  316. std::unique_lock<std::mutex> lock(mutex_tasks);
  317. if (task.id == -1) {
  318. task.id = id++;
  319. LOG_VERBOSE("new task id", {{"new_id", task.id}});
  320. }
  321. queue_tasks.push_back(std::move(task));
  322. condition_tasks.notify_one();
  323. return task.id;
  324. }
  325. // Add a new task, but defer until one slot is available
  326. void defer(server_task task) {
  327. std::unique_lock<std::mutex> lock(mutex_tasks);
  328. queue_tasks_deferred.push_back(std::move(task));
  329. }
  330. // Get the next id for creating anew task
  331. int get_new_id() {
  332. std::unique_lock<std::mutex> lock(mutex_tasks);
  333. int new_id = id++;
  334. LOG_VERBOSE("new task id", {{"new_id", new_id}});
  335. return new_id;
  336. }
  337. // Register function to process a new task
  338. void on_new_task(std::function<void(server_task &)> callback) {
  339. callback_new_task = std::move(callback);
  340. }
  341. // Register function to process a multitask when it is finished
  342. void on_finish_multitask(std::function<void(server_task_multi&)> callback) {
  343. callback_finish_multitask = std::move(callback);
  344. }
  345. // Register the function to be called when all slots data is ready to be processed
  346. void on_update_slots(std::function<void(void)> callback) {
  347. callback_update_slots = std::move(callback);
  348. }
  349. // Call when the state of one slot is changed
  350. void notify_slot_changed() {
  351. // move deferred tasks back to main loop
  352. std::unique_lock<std::mutex> lock(mutex_tasks);
  353. for (auto & task : queue_tasks_deferred) {
  354. queue_tasks.push_back(std::move(task));
  355. }
  356. queue_tasks_deferred.clear();
  357. }
  358. // end the start_loop routine
  359. void terminate() {
  360. std::unique_lock<std::mutex> lock(mutex_tasks);
  361. running = false;
  362. condition_tasks.notify_all();
  363. }
  364. /**
  365. * Main loop consists of these steps:
  366. * - Wait until a new task arrives
  367. * - Process the task (i.e. maybe copy data into slot)
  368. * - Check if multitask is finished
  369. * - Update all slots
  370. */
  371. void start_loop() {
  372. running = true;
  373. while (true) {
  374. LOG_VERBOSE("new task may arrive", {});
  375. while (true) {
  376. std::unique_lock<std::mutex> lock(mutex_tasks);
  377. if (queue_tasks.empty()) {
  378. lock.unlock();
  379. break;
  380. }
  381. server_task task = queue_tasks.front();
  382. queue_tasks.erase(queue_tasks.begin());
  383. lock.unlock();
  384. LOG_VERBOSE("callback_new_task", {{"id_task", task.id}});
  385. callback_new_task(task);
  386. }
  387. LOG_VERBOSE("update_multitasks", {});
  388. // check if we have any finished multitasks
  389. auto queue_iterator = queue_multitasks.begin();
  390. while (queue_iterator != queue_multitasks.end()) {
  391. if (queue_iterator->subtasks_remaining.empty()) {
  392. // all subtasks done == multitask is done
  393. server_task_multi current_multitask = *queue_iterator;
  394. callback_finish_multitask(current_multitask);
  395. // remove this multitask
  396. queue_iterator = queue_multitasks.erase(queue_iterator);
  397. } else {
  398. ++queue_iterator;
  399. }
  400. }
  401. // all tasks in the current loop is processed, slots data is now ready
  402. LOG_VERBOSE("callback_update_slots", {});
  403. callback_update_slots();
  404. LOG_VERBOSE("wait for new task", {});
  405. {
  406. std::unique_lock<std::mutex> lock(mutex_tasks);
  407. if (queue_tasks.empty()) {
  408. if (!running) {
  409. LOG_VERBOSE("ending start_loop", {});
  410. return;
  411. }
  412. condition_tasks.wait(lock, [&]{
  413. return (!queue_tasks.empty() || !running);
  414. });
  415. }
  416. }
  417. }
  418. }
  419. //
  420. // functions to manage multitasks
  421. //
  422. // add a multitask by specifying the id of all subtask (subtask is a server_task)
  423. void add_multitask(int id_multi, std::vector<int> & sub_ids) {
  424. std::lock_guard<std::mutex> lock(mutex_tasks);
  425. server_task_multi multi;
  426. multi.id = id_multi;
  427. std::copy(sub_ids.begin(), sub_ids.end(), std::inserter(multi.subtasks_remaining, multi.subtasks_remaining.end()));
  428. queue_multitasks.push_back(multi);
  429. }
  430. // updatethe remaining subtasks, while appending results to multitask
  431. void update_multitask(int id_multi, int id_sub, server_task_result & result) {
  432. std::lock_guard<std::mutex> lock(mutex_tasks);
  433. for (auto & multitask : queue_multitasks) {
  434. if (multitask.id == id_multi) {
  435. multitask.subtasks_remaining.erase(id_sub);
  436. multitask.results.push_back(result);
  437. }
  438. }
  439. }
  440. };
  441. struct server_response {
  442. typedef std::function<void(int, int, server_task_result &)> callback_multitask_t;
  443. callback_multitask_t callback_update_multitask;
  444. // for keeping track of all tasks waiting for the result
  445. std::set<int> waiting_task_ids;
  446. // the main result queue
  447. std::vector<server_task_result> queue_results;
  448. std::mutex mutex_results;
  449. std::condition_variable condition_results;
  450. // add the id_task to the list of tasks waiting for response
  451. void add_waiting_task_id(int id_task) {
  452. LOG_VERBOSE("waiting for task id", {{"id_task", id_task}});
  453. std::unique_lock<std::mutex> lock(mutex_results);
  454. waiting_task_ids.insert(id_task);
  455. }
  456. // when the request is finished, we can remove task associated with it
  457. void remove_waiting_task_id(int id_task) {
  458. LOG_VERBOSE("remove waiting for task id", {{"id_task", id_task}});
  459. std::unique_lock<std::mutex> lock(mutex_results);
  460. waiting_task_ids.erase(id_task);
  461. }
  462. // This function blocks the thread until there is a response for this id_task
  463. server_task_result recv(int id_task) {
  464. while (true) {
  465. std::unique_lock<std::mutex> lock(mutex_results);
  466. condition_results.wait(lock, [&]{
  467. return !queue_results.empty();
  468. });
  469. for (int i = 0; i < (int) queue_results.size(); i++) {
  470. if (queue_results[i].id == id_task) {
  471. assert(queue_results[i].id_multi == -1);
  472. server_task_result res = queue_results[i];
  473. queue_results.erase(queue_results.begin() + i);
  474. return res;
  475. }
  476. }
  477. }
  478. // should never reach here
  479. }
  480. // Register the function to update multitask
  481. void on_multitask_update(callback_multitask_t callback) {
  482. callback_update_multitask = std::move(callback);
  483. }
  484. // Send a new result to a waiting id_task
  485. void send(server_task_result result) {
  486. LOG_VERBOSE("send new result", {{"id_task", result.id}});
  487. std::unique_lock<std::mutex> lock(mutex_results);
  488. for (const auto & id_task : waiting_task_ids) {
  489. // LOG_TEE("waiting task id %i \n", id_task);
  490. // for now, tasks that have associated parent multitasks just get erased once multitask picks up the result
  491. if (result.id_multi == id_task) {
  492. LOG_VERBOSE("callback_update_multitask", {{"id_task", id_task}});
  493. callback_update_multitask(id_task, result.id, result);
  494. continue;
  495. }
  496. if (result.id == id_task) {
  497. LOG_VERBOSE("queue_results.push_back", {{"id_task", id_task}});
  498. queue_results.push_back(result);
  499. condition_results.notify_all();
  500. return;
  501. }
  502. }
  503. }
  504. };
  505. struct server_context {
  506. llama_model * model = nullptr;
  507. llama_context * ctx = nullptr;
  508. gpt_params params;
  509. llama_batch batch;
  510. bool clean_kv_cache = true;
  511. bool add_bos_token = true;
  512. int32_t n_ctx; // total context for all clients / slots
  513. // system prompt
  514. bool system_need_update = false;
  515. std::string system_prompt;
  516. std::vector<llama_token> system_tokens;
  517. std::string name_user; // this should be the antiprompt
  518. std::string name_assistant;
  519. // slots / clients
  520. std::vector<server_slot> slots;
  521. json default_generation_settings_for_props;
  522. server_queue queue_tasks;
  523. server_response queue_results;
  524. server_metrics metrics;
  525. ~server_context() {
  526. if (ctx) {
  527. llama_free(ctx);
  528. ctx = nullptr;
  529. }
  530. if (model) {
  531. llama_free_model(model);
  532. model = nullptr;
  533. }
  534. }
  535. bool load_model(const gpt_params & params_) {
  536. params = params_;
  537. // dedicate one sequence to the system prompt
  538. params.n_parallel += 1;
  539. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  540. params.n_parallel -= 1; // but be sneaky about it
  541. if (model == nullptr) {
  542. LOG_ERROR("unable to load model", {{"model", params.model}});
  543. return false;
  544. }
  545. n_ctx = llama_n_ctx(ctx);
  546. add_bos_token = llama_should_add_bos_token(model);
  547. return true;
  548. }
  549. bool validate_model_chat_template() const {
  550. llama_chat_message chat[] = {{"user", "test"}};
  551. const int res = llama_chat_apply_template(model, nullptr, chat, 1, true, nullptr, 0);
  552. return res > 0;
  553. }
  554. void init() {
  555. const int32_t n_ctx_slot = n_ctx / params.n_parallel;
  556. LOG_INFO("initializing slots", {{"n_slots", params.n_parallel}});
  557. for (int i = 0; i < params.n_parallel; i++) {
  558. server_slot slot;
  559. slot.id = i;
  560. slot.n_ctx = n_ctx_slot;
  561. slot.n_predict = params.n_predict;
  562. LOG_INFO("new slot", {
  563. {"id_slot", slot.id},
  564. {"n_ctx_slot", slot.n_ctx}
  565. });
  566. const int ga_n = params.grp_attn_n;
  567. const int ga_w = params.grp_attn_w;
  568. if (ga_n != 1) {
  569. GGML_ASSERT(ga_n > 0 && "ga_n must be positive"); // NOLINT
  570. GGML_ASSERT(ga_w % ga_n == 0 && "ga_w must be a multiple of ga_n"); // NOLINT
  571. //GGML_ASSERT(n_ctx_train % ga_w == 0 && "n_ctx_train must be a multiple of ga_w"); // NOLINT
  572. //GGML_ASSERT(n_ctx >= n_ctx_train * ga_n && "n_ctx must be at least n_ctx_train * ga_n"); // NOLINT
  573. LOG_INFO("slot self-extend", {
  574. {"id_slot", slot.id},
  575. {"ga_n", ga_n},
  576. {"ga_w", ga_w}
  577. });
  578. }
  579. slot.ga_i = 0;
  580. slot.ga_n = ga_n;
  581. slot.ga_w = ga_w;
  582. slot.reset();
  583. slots.push_back(slot);
  584. }
  585. default_generation_settings_for_props = get_formated_generation(slots.front());
  586. default_generation_settings_for_props["seed"] = -1;
  587. batch = llama_batch_init(n_ctx, 0, params.n_parallel);
  588. metrics.init();
  589. }
  590. std::vector<llama_token> tokenize(const json & json_prompt, bool add_bos) const {
  591. // TODO: currently, we tokenize using special tokens by default
  592. // this is not always correct (see https://github.com/ggerganov/llama.cpp/pull/4160#issuecomment-1824826216)
  593. // but it's better compared to completely ignoring ChatML and other chat templates
  594. const bool TMP_FORCE_SPECIAL = true;
  595. // If `add_bos` is true, we only add BOS, when json_prompt is a string,
  596. // or the first element of the json_prompt array is a string.
  597. std::vector<llama_token> prompt_tokens;
  598. if (json_prompt.is_array()) {
  599. bool first = true;
  600. for (const auto & p : json_prompt) {
  601. if (p.is_string()) {
  602. auto s = p.template get<std::string>();
  603. std::vector<llama_token> p;
  604. if (first) {
  605. p = ::llama_tokenize(ctx, s, add_bos, TMP_FORCE_SPECIAL);
  606. first = false;
  607. } else {
  608. p = ::llama_tokenize(ctx, s, false, TMP_FORCE_SPECIAL);
  609. }
  610. prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
  611. } else {
  612. if (first) {
  613. first = false;
  614. }
  615. prompt_tokens.push_back(p.template get<llama_token>());
  616. }
  617. }
  618. } else {
  619. auto s = json_prompt.template get<std::string>();
  620. prompt_tokens = ::llama_tokenize(ctx, s, add_bos, TMP_FORCE_SPECIAL);
  621. }
  622. return prompt_tokens;
  623. }
  624. server_slot * get_slot(int id) {
  625. int64_t t_last = ggml_time_us();
  626. server_slot * last_used = nullptr;
  627. for (server_slot & slot : slots) {
  628. if (slot.id == id && slot.available()) {
  629. return &slot;
  630. }
  631. // among all available slots, find the one that has been least recently used
  632. if (slot.available() && slot.t_last_used < t_last) {
  633. last_used = &slot;
  634. t_last = slot.t_last_used;
  635. }
  636. }
  637. return last_used;
  638. }
  639. bool launch_slot_with_task(server_slot & slot, const server_task & task) {
  640. slot_params default_params;
  641. llama_sampling_params default_sparams;
  642. auto & data = task.data;
  643. if (data.count("__oaicompat") != 0) {
  644. slot.oaicompat = true;
  645. slot.oaicompat_model = json_value(data, "model", std::string(DEFAULT_OAICOMPAT_MODEL));
  646. } else {
  647. slot.oaicompat = false;
  648. slot.oaicompat_model = "";
  649. }
  650. slot.params.stream = json_value(data, "stream", false);
  651. slot.params.cache_prompt = json_value(data, "cache_prompt", false);
  652. slot.params.n_predict = json_value(data, "n_predict", default_params.n_predict);
  653. slot.sparams.top_k = json_value(data, "top_k", default_sparams.top_k);
  654. slot.sparams.top_p = json_value(data, "top_p", default_sparams.top_p);
  655. slot.sparams.min_p = json_value(data, "min_p", default_sparams.min_p);
  656. slot.sparams.tfs_z = json_value(data, "tfs_z", default_sparams.tfs_z);
  657. slot.sparams.typical_p = json_value(data, "typical_p", default_sparams.typical_p);
  658. slot.sparams.temp = json_value(data, "temperature", default_sparams.temp);
  659. slot.sparams.dynatemp_range = json_value(data, "dynatemp_range", default_sparams.dynatemp_range);
  660. slot.sparams.dynatemp_exponent = json_value(data, "dynatemp_exponent", default_sparams.dynatemp_exponent);
  661. slot.sparams.penalty_last_n = json_value(data, "repeat_last_n", default_sparams.penalty_last_n);
  662. slot.sparams.penalty_repeat = json_value(data, "repeat_penalty", default_sparams.penalty_repeat);
  663. slot.sparams.penalty_freq = json_value(data, "frequency_penalty", default_sparams.penalty_freq);
  664. slot.sparams.penalty_present = json_value(data, "presence_penalty", default_sparams.penalty_present);
  665. slot.sparams.mirostat = json_value(data, "mirostat", default_sparams.mirostat);
  666. slot.sparams.mirostat_tau = json_value(data, "mirostat_tau", default_sparams.mirostat_tau);
  667. slot.sparams.mirostat_eta = json_value(data, "mirostat_eta", default_sparams.mirostat_eta);
  668. slot.sparams.penalize_nl = json_value(data, "penalize_nl", default_sparams.penalize_nl);
  669. slot.params.n_keep = json_value(data, "n_keep", slot.params.n_keep);
  670. slot.params.seed = json_value(data, "seed", default_params.seed);
  671. slot.sparams.grammar = json_value(data, "grammar", default_sparams.grammar);
  672. slot.sparams.n_probs = json_value(data, "n_probs", default_sparams.n_probs);
  673. slot.sparams.min_keep = json_value(data, "min_keep", default_sparams.min_keep);
  674. if (slot.params.cache_prompt && slot.ga_n != 1) {
  675. LOG_WARNING("cache_prompt is not supported with group-attention", {});
  676. slot.params.cache_prompt = false;
  677. }
  678. if (slot.n_predict > 0 && slot.params.n_predict > slot.n_predict) {
  679. // Might be better to reject the request with a 400 ?
  680. LOG_WARNING("Max tokens to predict exceeds server configuration", {
  681. {"params.n_predict", slot.params.n_predict},
  682. {"slot.n_predict", slot.n_predict},
  683. });
  684. slot.params.n_predict = slot.n_predict;
  685. }
  686. // infill
  687. slot.params.input_prefix = json_value(data, "input_prefix", default_params.input_prefix);
  688. slot.params.input_suffix = json_value(data, "input_suffix", default_params.input_suffix);
  689. // get prompt
  690. {
  691. const auto & prompt = data.find("prompt");
  692. if (prompt == data.end()) {
  693. send_error(task, "Either \"prompt\" or \"messages\" must be provided", ERROR_TYPE_INVALID_REQUEST);
  694. return false;
  695. } else {
  696. slot.prompt = *prompt;
  697. }
  698. if (slot.prompt.is_array() && slot.prompt.size() == 0) {
  699. send_error(task, "\"prompt\" cannot be an empty array", ERROR_TYPE_INVALID_REQUEST);
  700. return false;
  701. }
  702. }
  703. // penalize user-provided tokens
  704. {
  705. slot.sparams.penalty_prompt_tokens.clear();
  706. slot.sparams.use_penalty_prompt_tokens = false;
  707. const auto & penalty_prompt = data.find("penalty_prompt");
  708. if (penalty_prompt != data.end()) {
  709. if (penalty_prompt->is_string()) {
  710. const auto penalty_prompt_string = penalty_prompt->get<std::string>();
  711. slot.sparams.penalty_prompt_tokens = llama_tokenize(model, penalty_prompt_string, false);
  712. if (slot.params.n_predict > 0) {
  713. slot.sparams.penalty_prompt_tokens.reserve(slot.sparams.penalty_prompt_tokens.size() + slot.params.n_predict);
  714. }
  715. slot.sparams.use_penalty_prompt_tokens = true;
  716. LOG_VERBOSE("penalty_prompt_tokens", {
  717. {"id_slot", slot.id},
  718. {"tokens", slot.sparams.penalty_prompt_tokens},
  719. });
  720. }
  721. else if (penalty_prompt->is_array()) {
  722. const auto n_tokens = penalty_prompt->size();
  723. slot.sparams.penalty_prompt_tokens.reserve(n_tokens + std::max(0, slot.params.n_predict));
  724. const int n_vocab = llama_n_vocab(model);
  725. for (const auto & penalty_token : *penalty_prompt) {
  726. if (penalty_token.is_number_integer()) {
  727. const auto tok = penalty_token.get<llama_token>();
  728. if (tok >= 0 && tok < n_vocab) {
  729. slot.sparams.penalty_prompt_tokens.push_back(tok);
  730. }
  731. }
  732. }
  733. slot.sparams.use_penalty_prompt_tokens = true;
  734. LOG_VERBOSE("penalty_prompt_tokens", {
  735. {"id_slot", slot.id},
  736. {"tokens", slot.sparams.penalty_prompt_tokens},
  737. });
  738. }
  739. }
  740. }
  741. {
  742. slot.sparams.logit_bias.clear();
  743. if (json_value(data, "ignore_eos", false)) {
  744. slot.sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  745. }
  746. const auto & logit_bias = data.find("logit_bias");
  747. if (logit_bias != data.end() && logit_bias->is_array()) {
  748. const int n_vocab = llama_n_vocab(model);
  749. for (const auto & el : *logit_bias) {
  750. // TODO: we may want to throw errors here, in case "el" is incorrect
  751. if (el.is_array() && el.size() == 2) {
  752. float bias;
  753. if (el[1].is_number()) {
  754. bias = el[1].get<float>();
  755. } else if (el[1].is_boolean() && !el[1].get<bool>()) {
  756. bias = -INFINITY;
  757. } else {
  758. continue;
  759. }
  760. if (el[0].is_number_integer()) {
  761. llama_token tok = el[0].get<llama_token>();
  762. if (tok >= 0 && tok < n_vocab) {
  763. slot.sparams.logit_bias[tok] = bias;
  764. }
  765. } else if (el[0].is_string()) {
  766. auto toks = llama_tokenize(model, el[0].get<std::string>(), false);
  767. for (auto tok : toks) {
  768. slot.sparams.logit_bias[tok] = bias;
  769. }
  770. }
  771. }
  772. }
  773. }
  774. }
  775. {
  776. slot.params.antiprompt.clear();
  777. const auto & stop = data.find("stop");
  778. if (stop != data.end() && stop->is_array()) {
  779. for (const auto & word : *stop) {
  780. if (!word.empty()) {
  781. slot.params.antiprompt.push_back(word);
  782. }
  783. }
  784. }
  785. }
  786. {
  787. const auto & samplers_sequence = data.find("samplers");
  788. if (samplers_sequence != data.end() && samplers_sequence->is_array()) {
  789. std::vector<std::string> sampler_names;
  790. for (const auto & sampler_name : *samplers_sequence) {
  791. if (sampler_name.is_string()) {
  792. sampler_names.emplace_back(sampler_name);
  793. }
  794. }
  795. slot.sparams.samplers_sequence = sampler_types_from_names(sampler_names, false);
  796. } else {
  797. slot.sparams.samplers_sequence = default_sparams.samplers_sequence;
  798. }
  799. }
  800. {
  801. if (slot.ctx_sampling != nullptr) {
  802. llama_sampling_free(slot.ctx_sampling);
  803. }
  804. slot.ctx_sampling = llama_sampling_init(slot.sparams);
  805. if (slot.ctx_sampling == nullptr) {
  806. // for now, the only error that may happen here is invalid grammar
  807. send_error(task, "Failed to parse grammar", ERROR_TYPE_INVALID_REQUEST);
  808. return false;
  809. }
  810. llama_set_rng_seed(ctx, slot.params.seed);
  811. }
  812. slot.command = SLOT_COMMAND_LOAD_PROMPT;
  813. slot.prompt_tokens.clear();
  814. LOG_INFO("slot is processing task", {
  815. {"id_slot", slot.id},
  816. {"id_task", slot.id_task},
  817. });
  818. return true;
  819. }
  820. void kv_cache_clear() {
  821. LOG_VERBOSE("clearing KV cache", {});
  822. // clear the entire KV cache
  823. llama_kv_cache_clear(ctx);
  824. clean_kv_cache = false;
  825. }
  826. void system_prompt_update() {
  827. LOG_VERBOSE("system prompt update", {
  828. {"system_prompt", system_prompt},
  829. });
  830. kv_cache_clear();
  831. system_tokens.clear();
  832. if (!system_prompt.empty()) {
  833. system_tokens = ::llama_tokenize(ctx, system_prompt, add_bos_token);
  834. llama_batch_clear(batch);
  835. for (int i = 0; i < (int)system_tokens.size(); ++i) {
  836. llama_batch_add(batch, system_tokens[i], i, { 0 }, false);
  837. }
  838. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += params.n_batch) {
  839. const int32_t n_tokens = std::min(params.n_batch, (int32_t) (batch.n_tokens - i));
  840. llama_batch batch_view = {
  841. n_tokens,
  842. batch.token + i,
  843. nullptr,
  844. batch.pos + i,
  845. batch.n_seq_id + i,
  846. batch.seq_id + i,
  847. batch.logits + i,
  848. 0, 0, 0, // unused
  849. };
  850. if (llama_decode(ctx, batch_view) != 0) {
  851. LOG_TEE("%s: llama_decode() failed\n", __func__);
  852. return;
  853. }
  854. }
  855. // assign the system KV cache to all parallel sequences
  856. for (int32_t i = 1; i <= params.n_parallel; ++i) {
  857. llama_kv_cache_seq_cp(ctx, 0, i, -1, -1);
  858. }
  859. }
  860. system_need_update = false;
  861. }
  862. void system_prompt_set(const json & sys_props) {
  863. system_prompt = sys_props.value("prompt", "");
  864. name_user = sys_props.value("anti_prompt", "");
  865. name_assistant = sys_props.value("assistant_name", "");
  866. LOG_VERBOSE("system prompt process", {
  867. {"system_prompt", system_prompt},
  868. {"name_user", name_user},
  869. {"name_assistant", name_assistant},
  870. });
  871. // release all slots
  872. for (server_slot & slot : slots) {
  873. slot.release();
  874. }
  875. system_need_update = true;
  876. }
  877. bool process_token(completion_token_output & result, server_slot & slot) {
  878. // remember which tokens were sampled - used for repetition penalties during sampling
  879. const std::string token_str = llama_token_to_piece(ctx, result.tok);
  880. slot.sampled = result.tok;
  881. // search stop word and delete it
  882. slot.generated_text += token_str;
  883. slot.has_next_token = true;
  884. if (slot.ctx_sampling->params.use_penalty_prompt_tokens && result.tok != -1) {
  885. // we can change penalty_prompt_tokens because it is always created from scratch each request
  886. slot.ctx_sampling->params.penalty_prompt_tokens.push_back(result.tok);
  887. }
  888. // check if there is incomplete UTF-8 character at the end
  889. bool incomplete = false;
  890. for (unsigned i = 1; i < 5 && i <= slot.generated_text.size(); ++i) {
  891. unsigned char c = slot.generated_text[slot.generated_text.size() - i];
  892. if ((c & 0xC0) == 0x80) {
  893. // continuation byte: 10xxxxxx
  894. continue;
  895. }
  896. if ((c & 0xE0) == 0xC0) {
  897. // 2-byte character: 110xxxxx ...
  898. incomplete = i < 2;
  899. } else if ((c & 0xF0) == 0xE0) {
  900. // 3-byte character: 1110xxxx ...
  901. incomplete = i < 3;
  902. } else if ((c & 0xF8) == 0xF0) {
  903. // 4-byte character: 11110xxx ...
  904. incomplete = i < 4;
  905. }
  906. // else 1-byte character or invalid byte
  907. break;
  908. }
  909. if (!incomplete) {
  910. size_t pos = std::min(slot.n_sent_text, slot.generated_text.size());
  911. const std::string str_test = slot.generated_text.substr(pos);
  912. bool is_stop_full = false;
  913. size_t stop_pos = slot.find_stopping_strings(str_test, token_str.size(), STOP_TYPE_FULL);
  914. if (stop_pos != std::string::npos) {
  915. is_stop_full = true;
  916. slot.generated_text.erase(
  917. slot.generated_text.begin() + pos + stop_pos,
  918. slot.generated_text.end());
  919. pos = std::min(slot.n_sent_text, slot.generated_text.size());
  920. } else {
  921. is_stop_full = false;
  922. stop_pos = slot.find_stopping_strings(str_test, token_str.size(), STOP_TYPE_PARTIAL);
  923. }
  924. // check if there is any token to predict
  925. if (stop_pos == std::string::npos || (!slot.has_next_token && !is_stop_full && stop_pos > 0)) {
  926. // no send the stop word in the response
  927. result.text_to_send = slot.generated_text.substr(pos, std::string::npos);
  928. slot.n_sent_text += result.text_to_send.size();
  929. // add the token to slot queue and cache
  930. }
  931. slot.add_token_string(result);
  932. if (slot.params.stream) {
  933. send_partial_response(slot, result);
  934. }
  935. }
  936. if (incomplete) {
  937. slot.has_next_token = true;
  938. }
  939. // check the limits
  940. if (slot.n_decoded > 0 && slot.has_next_token && !slot.has_budget(params)) {
  941. slot.stopped_limit = true;
  942. slot.has_next_token = false;
  943. LOG_VERBOSE("stopped by limit", {
  944. {"id_slot", slot.id},
  945. {"id_task", slot.id_task},
  946. {"n_decoded", slot.n_decoded},
  947. {"n_predict", slot.params.n_predict},
  948. });
  949. }
  950. if (result.tok == llama_token_eos(model)) {
  951. slot.stopped_eos = true;
  952. slot.has_next_token = false;
  953. LOG_VERBOSE("eos token found", {});
  954. }
  955. LOG_VERBOSE("next token", {
  956. {"id_slot", slot.id},
  957. {"id_task", slot.id_task},
  958. {"token", result.tok},
  959. {"token_text", tokens_to_output_formatted_string(ctx, result.tok)},
  960. {"has_next_token", slot.has_next_token},
  961. {"n_remain", slot.n_remaining},
  962. {"n_decoded", slot.n_decoded},
  963. {"stopped_eos", slot.stopped_eos},
  964. {"stopped_word", slot.stopped_word},
  965. {"stopped_limit", slot.stopped_limit},
  966. {"stopping_word", slot.stopping_word},
  967. });
  968. return slot.has_next_token; // continue
  969. }
  970. json get_formated_generation(const server_slot & slot) const {
  971. const auto eos_bias = slot.sparams.logit_bias.find(llama_token_eos(model));
  972. const bool ignore_eos = eos_bias != slot.sparams.logit_bias.end() && eos_bias->second < 0.0f && std::isinf(eos_bias->second);
  973. std::vector<std::string> samplers_sequence;
  974. samplers_sequence.reserve(slot.sparams.samplers_sequence.size());
  975. for (const auto & sampler_type : slot.sparams.samplers_sequence) {
  976. samplers_sequence.emplace_back(sampler_type_to_name_string(sampler_type));
  977. }
  978. return json {
  979. {"n_ctx", slot.n_ctx},
  980. {"n_predict", slot.n_predict},
  981. {"model", params.model_alias},
  982. {"seed", slot.params.seed},
  983. {"temperature", slot.sparams.temp},
  984. {"dynatemp_range", slot.sparams.dynatemp_range},
  985. {"dynatemp_exponent", slot.sparams.dynatemp_exponent},
  986. {"top_k", slot.sparams.top_k},
  987. {"top_p", slot.sparams.top_p},
  988. {"min_p", slot.sparams.min_p},
  989. {"tfs_z", slot.sparams.tfs_z},
  990. {"typical_p", slot.sparams.typical_p},
  991. {"repeat_last_n", slot.sparams.penalty_last_n},
  992. {"repeat_penalty", slot.sparams.penalty_repeat},
  993. {"presence_penalty", slot.sparams.penalty_present},
  994. {"frequency_penalty", slot.sparams.penalty_freq},
  995. {"penalty_prompt_tokens", slot.sparams.penalty_prompt_tokens},
  996. {"use_penalty_prompt_tokens", slot.sparams.use_penalty_prompt_tokens},
  997. {"mirostat", slot.sparams.mirostat},
  998. {"mirostat_tau", slot.sparams.mirostat_tau},
  999. {"mirostat_eta", slot.sparams.mirostat_eta},
  1000. {"penalize_nl", slot.sparams.penalize_nl},
  1001. {"stop", slot.params.antiprompt},
  1002. {"n_predict", slot.params.n_predict},
  1003. {"n_keep", params.n_keep},
  1004. {"ignore_eos", ignore_eos},
  1005. {"stream", slot.params.stream},
  1006. {"logit_bias", slot.sparams.logit_bias},
  1007. {"n_probs", slot.sparams.n_probs},
  1008. {"min_keep", slot.sparams.min_keep},
  1009. {"grammar", slot.sparams.grammar},
  1010. {"samplers", samplers_sequence}
  1011. };
  1012. }
  1013. void send_error(const server_task & task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1014. send_error(task.id, task.id_multi, error, type);
  1015. }
  1016. void send_error(const server_slot & slot, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1017. send_error(slot.id_task, slot.id_multi, error, type);
  1018. }
  1019. void send_error(const int id_task, const int id_multi, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1020. LOG_TEE("task %i - error: %s\n", id_task, error.c_str());
  1021. server_task_result res;
  1022. res.id = id_task;
  1023. res.id_multi = id_multi;
  1024. res.stop = false;
  1025. res.error = true;
  1026. res.data = format_error_response(error, type);
  1027. queue_results.send(res);
  1028. }
  1029. void send_partial_response(server_slot & slot, completion_token_output tkn) {
  1030. server_task_result res;
  1031. res.id = slot.id_task;
  1032. res.id_multi = slot.id_multi;
  1033. res.error = false;
  1034. res.stop = false;
  1035. res.data = json {
  1036. {"content", tkn.text_to_send},
  1037. {"stop", false},
  1038. {"id_slot", slot.id},
  1039. {"multimodal", false}
  1040. };
  1041. if (slot.sparams.n_probs > 0) {
  1042. const std::vector<llama_token> to_send_toks = llama_tokenize(ctx, tkn.text_to_send, false);
  1043. const size_t probs_pos = std::min(slot.n_sent_token_probs, slot.generated_token_probs.size());
  1044. const size_t probs_stop_pos = std::min(slot.n_sent_token_probs + to_send_toks.size(), slot.generated_token_probs.size());
  1045. std::vector<completion_token_output> probs_output;
  1046. if (probs_pos < probs_stop_pos) {
  1047. probs_output = std::vector<completion_token_output>(
  1048. slot.generated_token_probs.begin() + probs_pos,
  1049. slot.generated_token_probs.begin() + probs_stop_pos);
  1050. }
  1051. slot.n_sent_token_probs = probs_stop_pos;
  1052. res.data["completion_probabilities"] = probs_vector_to_json(ctx, probs_output);
  1053. }
  1054. if (slot.oaicompat) {
  1055. res.data["oaicompat_token_ctr"] = slot.n_decoded;
  1056. res.data["model"] = slot.oaicompat_model;
  1057. }
  1058. queue_results.send(res);
  1059. }
  1060. void send_final_response(const server_slot & slot) {
  1061. server_task_result res;
  1062. res.id = slot.id_task;
  1063. res.id_multi = slot.id_multi;
  1064. res.error = false;
  1065. res.stop = true;
  1066. res.data = json {
  1067. {"content", !slot.params.stream ? slot.generated_text : ""},
  1068. {"id_slot", slot.id},
  1069. {"stop", true},
  1070. {"model", params.model_alias},
  1071. {"tokens_predicted", slot.n_decoded},
  1072. {"tokens_evaluated", slot.n_prompt_tokens},
  1073. {"generation_settings", get_formated_generation(slot)},
  1074. {"prompt", slot.prompt},
  1075. {"truncated", slot.truncated},
  1076. {"stopped_eos", slot.stopped_eos},
  1077. {"stopped_word", slot.stopped_word},
  1078. {"stopped_limit", slot.stopped_limit},
  1079. {"stopping_word", slot.stopping_word},
  1080. {"tokens_cached", slot.n_past},
  1081. {"timings", slot.get_formated_timings()}
  1082. };
  1083. if (slot.sparams.n_probs > 0) {
  1084. std::vector<completion_token_output> probs;
  1085. if (!slot.params.stream && slot.stopped_word) {
  1086. const std::vector<llama_token> stop_word_toks = llama_tokenize(ctx, slot.stopping_word, false);
  1087. probs = std::vector<completion_token_output>(
  1088. slot.generated_token_probs.begin(),
  1089. slot.generated_token_probs.end() - stop_word_toks.size());
  1090. } else {
  1091. probs = std::vector<completion_token_output>(
  1092. slot.generated_token_probs.begin(),
  1093. slot.generated_token_probs.end());
  1094. }
  1095. res.data["completion_probabilities"] = probs_vector_to_json(ctx, probs);
  1096. }
  1097. if (slot.oaicompat) {
  1098. res.data["oaicompat_token_ctr"] = slot.n_decoded;
  1099. res.data["model"] = slot.oaicompat_model;
  1100. }
  1101. queue_results.send(res);
  1102. }
  1103. void send_embedding(const server_slot & slot, const llama_batch & batch) {
  1104. server_task_result res;
  1105. res.id = slot.id_task;
  1106. res.id_multi = slot.id_multi;
  1107. res.error = false;
  1108. res.stop = true;
  1109. const int n_embd = llama_n_embd(model);
  1110. std::vector<float> embd_res(n_embd, 0.0f);
  1111. for (int i = 0; i < batch.n_tokens; ++i) {
  1112. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id + 1) {
  1113. continue;
  1114. }
  1115. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1116. if (embd == NULL) {
  1117. embd = llama_get_embeddings_ith(ctx, i);
  1118. }
  1119. if (embd == NULL) {
  1120. LOG_ERROR("failed to get embeddings", {
  1121. {"token", batch.token [i]},
  1122. {"seq_id", batch.seq_id[i][0]}
  1123. });
  1124. res.data = json {
  1125. {"embedding", std::vector<float>(n_embd, 0.0f)},
  1126. };
  1127. continue;
  1128. }
  1129. llama_embd_normalize(embd, embd_res.data(), n_embd);
  1130. res.data = json {
  1131. {"embedding", embd_res},
  1132. };
  1133. }
  1134. queue_results.send(res);
  1135. }
  1136. void request_completion(int id_task, int id_multi, json data, bool infill, bool embedding) {
  1137. server_task task;
  1138. task.id = id_task;
  1139. task.id_multi = id_multi;
  1140. task.id_target = 0;
  1141. task.data = std::move(data);
  1142. task.infill = infill;
  1143. task.embedding = embedding;
  1144. task.type = SERVER_TASK_TYPE_COMPLETION;
  1145. // when a completion task's prompt array is not a singleton, we split it into multiple requests
  1146. // otherwise, it's a single-prompt task, we actually queue it
  1147. // if there's numbers in the prompt array it will be treated as an array of tokens
  1148. if (task.data.count("prompt") != 0 && task.data.at("prompt").size() > 1) {
  1149. bool numbers = false;
  1150. for (const auto & e : task.data.at("prompt")) {
  1151. if (e.is_number()) {
  1152. numbers = true;
  1153. break;
  1154. }
  1155. }
  1156. // NOTE: split_multiprompt_task() does not handle a mix of strings and numbers,
  1157. // it will completely stall the server. I don't know where the bug for this is.
  1158. //
  1159. // if there are numbers, it needs to be treated like a single prompt,
  1160. // queue_tasks handles a mix of strings and numbers just fine.
  1161. if (numbers) {
  1162. queue_tasks.post(task);
  1163. } else {
  1164. split_multiprompt_task(id_task, task);
  1165. }
  1166. } else {
  1167. queue_tasks.post(task);
  1168. }
  1169. }
  1170. void request_cancel(int id_task) {
  1171. server_task task;
  1172. task.type = SERVER_TASK_TYPE_CANCEL;
  1173. task.id_target = id_task;
  1174. queue_tasks.post(task);
  1175. }
  1176. void split_multiprompt_task(int id_multi, const server_task & multiprompt_task) {
  1177. const int prompt_count = multiprompt_task.data.at("prompt").size();
  1178. if (prompt_count <= 1) {
  1179. send_error(multiprompt_task, "error while handling multiple prompts");
  1180. return;
  1181. }
  1182. // generate all the ID for subtask
  1183. std::vector<int> subtask_ids(prompt_count);
  1184. for (int i = 0; i < prompt_count; i++) {
  1185. subtask_ids[i] = queue_tasks.get_new_id();
  1186. }
  1187. // queue up the multitask so we can track its subtask progression
  1188. queue_tasks.add_multitask(id_multi, subtask_ids);
  1189. // add subtasks
  1190. for (int i = 0; i < prompt_count; i++) {
  1191. json subtask_data = multiprompt_task.data;
  1192. subtask_data["prompt"] = subtask_data["prompt"][i];
  1193. // subtasks inherit everything else (infill mode, embedding mode, etc.)
  1194. request_completion(subtask_ids[i], id_multi, subtask_data, multiprompt_task.infill, multiprompt_task.embedding);
  1195. }
  1196. }
  1197. void process_single_task(const server_task & task) {
  1198. switch (task.type) {
  1199. case SERVER_TASK_TYPE_COMPLETION:
  1200. {
  1201. server_slot * slot = get_slot(json_value(task.data, "id_slot", -1));
  1202. if (slot == nullptr) {
  1203. // if no slot is available, we defer this task for processing later
  1204. LOG_VERBOSE("no slot is available", {{"id_task", task.id}});
  1205. queue_tasks.defer(task);
  1206. break;
  1207. }
  1208. if (task.data.contains("system_prompt")) {
  1209. system_prompt_set(task.data["system_prompt"]);
  1210. for (server_slot & slot : slots) {
  1211. slot.n_past = 0;
  1212. slot.n_past_se = 0;
  1213. }
  1214. }
  1215. slot->reset();
  1216. slot->id_task = task.id;
  1217. slot->id_multi = task.id_multi;
  1218. slot->infill = task.infill;
  1219. slot->embedding = task.embedding;
  1220. if (!launch_slot_with_task(*slot, task)) {
  1221. LOG_ERROR("error while launching slot", task.data);
  1222. break;
  1223. }
  1224. } break;
  1225. case SERVER_TASK_TYPE_CANCEL:
  1226. {
  1227. // release slot linked with the task id
  1228. for (auto & slot : slots) {
  1229. if (slot.id_task == task.id_target) {
  1230. slot.release();
  1231. break;
  1232. }
  1233. }
  1234. } break;
  1235. case SERVER_TASK_TYPE_NEXT_RESPONSE:
  1236. {
  1237. // do nothing
  1238. } break;
  1239. case SERVER_TASK_TYPE_METRICS:
  1240. {
  1241. json slots_data = json::array();
  1242. int n_idle_slots = 0;
  1243. int n_processing_slots = 0;
  1244. for (server_slot & slot : slots) {
  1245. json slot_data = get_formated_generation(slot);
  1246. slot_data["id"] = slot.id;
  1247. slot_data["id_task"] = slot.id_task;
  1248. slot_data["state"] = slot.state;
  1249. slot_data["prompt"] = slot.prompt;
  1250. slot_data["next_token"] = {
  1251. {"has_next_token", slot.has_next_token},
  1252. {"n_remain", slot.n_remaining},
  1253. {"n_decoded", slot.n_decoded},
  1254. {"stopped_eos", slot.stopped_eos},
  1255. {"stopped_word", slot.stopped_word},
  1256. {"stopped_limit", slot.stopped_limit},
  1257. {"stopping_word", slot.stopping_word},
  1258. };
  1259. if (slot_data["state"] == SLOT_STATE_IDLE) {
  1260. n_idle_slots++;
  1261. } else {
  1262. n_processing_slots++;
  1263. }
  1264. slots_data.push_back(slot_data);
  1265. }
  1266. LOG_INFO("slot data", {
  1267. {"id_task", task.id},
  1268. {"n_idle_slots", n_idle_slots},
  1269. {"n_processing_slots", n_processing_slots}
  1270. });
  1271. LOG_VERBOSE("slot data", {
  1272. {"id_task", task.id},
  1273. {"n_idle_slots", n_idle_slots},
  1274. {"n_processing_slots", n_processing_slots},
  1275. {"slots", slots_data}
  1276. });
  1277. server_task_result res;
  1278. res.id = task.id;
  1279. res.id_multi = task.id_multi;
  1280. res.stop = true;
  1281. res.error = false;
  1282. res.data = {
  1283. { "idle", n_idle_slots },
  1284. { "processing", n_processing_slots },
  1285. { "deferred", queue_tasks.queue_tasks_deferred.size() },
  1286. { "t_start", metrics.t_start},
  1287. { "n_prompt_tokens_processed_total", metrics.n_prompt_tokens_processed_total},
  1288. { "t_tokens_generation_total", metrics.t_tokens_generation_total},
  1289. { "n_tokens_predicted_total", metrics.n_tokens_predicted_total},
  1290. { "t_prompt_processing_total", metrics.t_prompt_processing_total},
  1291. { "n_prompt_tokens_processed", metrics.n_prompt_tokens_processed},
  1292. { "t_prompt_processing", metrics.t_prompt_processing},
  1293. { "n_tokens_predicted", metrics.n_tokens_predicted},
  1294. { "t_tokens_generation", metrics.t_tokens_generation},
  1295. { "kv_cache_tokens_count", llama_get_kv_cache_token_count(ctx)},
  1296. { "kv_cache_used_cells", llama_get_kv_cache_used_cells(ctx)},
  1297. { "slots", slots_data },
  1298. };
  1299. if (json_value(task.data, "reset_bucket", false)) {
  1300. metrics.reset_bucket();
  1301. }
  1302. queue_results.send(res);
  1303. } break;
  1304. }
  1305. }
  1306. void on_finish_multitask(const server_task_multi & multitask) {
  1307. // all subtasks done == multitask is done
  1308. server_task_result result;
  1309. result.id = multitask.id;
  1310. result.stop = true;
  1311. result.error = false;
  1312. // collect json results into one json result
  1313. std::vector<json> result_jsons;
  1314. for (const auto & subres : multitask.results) {
  1315. result_jsons.push_back(subres.data);
  1316. result.error = result.error && subres.error;
  1317. }
  1318. result.data = json {
  1319. { "results", result_jsons }
  1320. };
  1321. queue_results.send(result);
  1322. }
  1323. void update_slots() {
  1324. if (system_need_update) {
  1325. system_prompt_update();
  1326. }
  1327. // release slots
  1328. for (auto & slot : slots) {
  1329. if (slot.command == SLOT_COMMAND_RELEASE) {
  1330. slot.state = SLOT_STATE_IDLE;
  1331. slot.command = SLOT_COMMAND_NONE;
  1332. slot.t_last_used = ggml_time_us();
  1333. LOG_INFO("slot released", {
  1334. {"id_slot", slot.id},
  1335. {"id_task", slot.id_task},
  1336. {"n_ctx", n_ctx},
  1337. {"n_past", slot.n_past},
  1338. {"n_system_tokens", system_tokens.size()},
  1339. {"n_cache_tokens", slot.cache_tokens.size()},
  1340. {"truncated", slot.truncated}
  1341. });
  1342. queue_tasks.notify_slot_changed();
  1343. }
  1344. }
  1345. // check if all slots are idle
  1346. {
  1347. bool all_idle = true;
  1348. for (auto & slot : slots) {
  1349. if (slot.state != SLOT_STATE_IDLE || slot.command != SLOT_COMMAND_NONE) {
  1350. all_idle = false;
  1351. break;
  1352. }
  1353. }
  1354. if (all_idle) {
  1355. LOG_INFO("all slots are idle", {});
  1356. if (system_prompt.empty() && clean_kv_cache) {
  1357. kv_cache_clear();
  1358. }
  1359. return;
  1360. }
  1361. }
  1362. {
  1363. LOG_VERBOSE("posting NEXT_RESPONSE", {});
  1364. server_task task;
  1365. task.type = SERVER_TASK_TYPE_NEXT_RESPONSE;
  1366. task.id_target = -1;
  1367. queue_tasks.post(task);
  1368. }
  1369. // apply context-shift if needed
  1370. // TODO: simplify and improve
  1371. for (server_slot & slot : slots) {
  1372. if (slot.ga_n == 1) {
  1373. if (slot.is_processing() && (int) system_tokens.size() + slot.n_past >= slot.n_ctx - 1) {
  1374. // Shift context
  1375. const int n_keep = slot.params.n_keep + add_bos_token;
  1376. const int n_left = (int) system_tokens.size() + slot.n_past - n_keep;
  1377. const int n_discard = n_left / 2;
  1378. LOG_INFO("slot context shift", {
  1379. {"id_slot", slot.id},
  1380. {"id_task", slot.id_task},
  1381. {"n_keep", n_keep},
  1382. {"n_left", n_left},
  1383. {"n_discard", n_discard},
  1384. {"n_ctx", n_ctx},
  1385. {"n_past", slot.n_past},
  1386. {"n_system_tokens", system_tokens.size()},
  1387. {"n_cache_tokens", slot.cache_tokens.size()}
  1388. });
  1389. llama_kv_cache_seq_rm (ctx, slot.id + 1, n_keep , n_keep + n_discard);
  1390. llama_kv_cache_seq_add(ctx, slot.id + 1, n_keep + n_discard, system_tokens.size() + slot.n_past, -n_discard);
  1391. if (slot.params.cache_prompt) {
  1392. for (size_t i = n_keep + n_discard; i < slot.cache_tokens.size(); i++) {
  1393. slot.cache_tokens[i - n_discard] = slot.cache_tokens[i];
  1394. }
  1395. slot.cache_tokens.resize(slot.cache_tokens.size() - n_discard);
  1396. }
  1397. slot.n_past -= n_discard;
  1398. slot.truncated = true;
  1399. }
  1400. }
  1401. }
  1402. // start populating the batch for this iteration
  1403. llama_batch_clear(batch);
  1404. // frist, add sampled tokens from any ongoing sequences
  1405. for (auto & slot : slots) {
  1406. if (slot.state == SLOT_STATE_IDLE) {
  1407. continue;
  1408. }
  1409. slot.i_batch = batch.n_tokens;
  1410. const int32_t slot_npast = slot.n_past_se > 0 ? slot.n_past_se : slot.n_past;
  1411. // TODO: we always have to take into account the "system_tokens"
  1412. // this is not great and needs to be improved somehow
  1413. llama_batch_add(batch, slot.sampled, system_tokens.size() + slot_npast, { slot.id + 1 }, true);
  1414. slot.n_past += 1;
  1415. if (slot.params.cache_prompt) {
  1416. slot.cache_tokens.push_back(slot.sampled);
  1417. }
  1418. LOG_VERBOSE("slot decode token", {
  1419. {"id_slot", slot.id},
  1420. {"id_task", slot.id_task},
  1421. {"n_ctx", n_ctx},
  1422. {"n_past", slot.n_past},
  1423. {"n_system_tokens", system_tokens.size()},
  1424. {"n_cache_tokens", slot.cache_tokens.size()},
  1425. {"truncated", slot.truncated}
  1426. });
  1427. }
  1428. // process in chunks of params.n_batch
  1429. int32_t n_batch = params.n_batch;
  1430. // next, batch any pending prompts without exceeding n_batch
  1431. if (params.cont_batching || batch.n_tokens == 0) {
  1432. for (auto & slot : slots) {
  1433. // this slot still has a prompt to be processed
  1434. if (slot.state == SLOT_STATE_IDLE && slot.command == SLOT_COMMAND_LOAD_PROMPT) {
  1435. auto & prompt_tokens = slot.prompt_tokens;
  1436. // we haven't tokenized the prompt yet - do it now:
  1437. if (prompt_tokens.empty()) {
  1438. LOG_VERBOSE("tokenizing prompt", {
  1439. {"id_slot", slot.id},
  1440. {"id_task", slot.id_task}
  1441. });
  1442. slot.t_start_process_prompt = ggml_time_us();
  1443. slot.t_start_generation = 0;
  1444. if (slot.infill) {
  1445. bool suff_rm_leading_spc = true;
  1446. if (params.input_suffix.find_first_of(' ') == 0 && params.input_suffix.size() > 1) {
  1447. params.input_suffix.erase(0, 1);
  1448. suff_rm_leading_spc = false;
  1449. }
  1450. auto prefix_tokens = tokenize(slot.params.input_prefix, false);
  1451. auto suffix_tokens = tokenize(slot.params.input_suffix, false);
  1452. const int space_token = 29871; // TODO: this should not be hardcoded
  1453. if (suff_rm_leading_spc && !suffix_tokens.empty() && suffix_tokens[0] == space_token) {
  1454. suffix_tokens.erase(suffix_tokens.begin());
  1455. }
  1456. prefix_tokens.insert(prefix_tokens.begin(), llama_token_prefix(model));
  1457. prefix_tokens.insert(prefix_tokens.begin(), llama_token_bos(model)); // always add BOS
  1458. prefix_tokens.insert(prefix_tokens.end(), llama_token_suffix(model));
  1459. prefix_tokens.insert(prefix_tokens.end(), suffix_tokens.begin(), suffix_tokens.end());
  1460. prefix_tokens.push_back(llama_token_middle(model));
  1461. prompt_tokens = prefix_tokens;
  1462. } else {
  1463. prompt_tokens = tokenize(slot.prompt, system_prompt.empty() && add_bos_token); // add BOS if there isn't system prompt
  1464. }
  1465. slot.n_past = 0;
  1466. slot.n_prompt_tokens = prompt_tokens.size();
  1467. LOG_VERBOSE("prompt tokenized", {
  1468. {"id_slot", slot.id},
  1469. {"id_task", slot.id_task},
  1470. {"n_ctx", slot.n_ctx},
  1471. {"n_keep", slot.params.n_keep},
  1472. {"n_prompt_tokens", slot.n_prompt_tokens},
  1473. {"prompt_tokens", tokens_to_str(ctx, prompt_tokens.cbegin(), prompt_tokens.cend())},
  1474. });
  1475. // empty prompt passed -> release the slot and send empty response
  1476. if (prompt_tokens.empty()) {
  1477. LOG_INFO("empty prompt - releasing slot", {
  1478. {"id_slot", slot.id},
  1479. {"id_task", slot.id_task}
  1480. });
  1481. slot.state = SLOT_STATE_PROCESSING;
  1482. slot.command = SLOT_COMMAND_NONE;
  1483. slot.release();
  1484. slot.print_timings();
  1485. send_final_response(slot);
  1486. continue;
  1487. }
  1488. if (slot.embedding) {
  1489. // this prompt is too large to process - discard it
  1490. if (slot.n_prompt_tokens > n_batch) {
  1491. slot.state = SLOT_STATE_PROCESSING;
  1492. slot.command = SLOT_COMMAND_NONE;
  1493. slot.release();
  1494. slot.print_timings();
  1495. send_final_response(slot);
  1496. continue;
  1497. }
  1498. } else {
  1499. if (slot.params.n_keep < 0) {
  1500. slot.params.n_keep = slot.n_prompt_tokens;
  1501. }
  1502. slot.params.n_keep = std::min(slot.n_ctx - 4, slot.params.n_keep);
  1503. // if input prompt is too big, truncate it (if group attention self-extend is disabled)
  1504. if (slot.ga_n == 1 && slot.n_prompt_tokens >= slot.n_ctx) {
  1505. const int n_left = slot.n_ctx - slot.params.n_keep;
  1506. const int n_block_size = n_left / 2;
  1507. const int erased_blocks = (slot.n_prompt_tokens - slot.params.n_keep - n_block_size) / n_block_size;
  1508. std::vector<llama_token> new_tokens(
  1509. prompt_tokens.begin(),
  1510. prompt_tokens.begin() + slot.params.n_keep);
  1511. new_tokens.insert(
  1512. new_tokens.end(),
  1513. prompt_tokens.begin() + slot.params.n_keep + erased_blocks * n_block_size,
  1514. prompt_tokens.end());
  1515. prompt_tokens = std::move(new_tokens);
  1516. slot.truncated = true;
  1517. slot.n_prompt_tokens = prompt_tokens.size();
  1518. LOG_VERBOSE("input truncated", {
  1519. {"id_slot", slot.id},
  1520. {"id_task", slot.id_task},
  1521. {"n_ctx", slot.n_ctx},
  1522. {"n_keep", slot.params.n_keep},
  1523. {"n_left", n_left},
  1524. {"n_prompt_tokens", slot.n_prompt_tokens},
  1525. {"prompt_tokens", tokens_to_str(ctx, prompt_tokens.cbegin(), prompt_tokens.cend())},
  1526. });
  1527. GGML_ASSERT(slot.n_prompt_tokens < slot.n_ctx);
  1528. }
  1529. llama_sampling_reset(slot.ctx_sampling);
  1530. if (!slot.params.cache_prompt) {
  1531. slot.n_past_se = 0;
  1532. slot.ga_i = 0;
  1533. } else {
  1534. GGML_ASSERT(slot.ga_n == 1);
  1535. // reuse any previously computed tokens that are common with the new prompt
  1536. slot.n_past = common_part(slot.cache_tokens, prompt_tokens);
  1537. // push the prompt into the sampling context (do not apply grammar)
  1538. for (int i = 0; i < slot.n_past; ++i) {
  1539. llama_sampling_accept(slot.ctx_sampling, ctx, slot.cache_tokens[i], false);
  1540. }
  1541. }
  1542. }
  1543. if (slot.n_past == slot.n_prompt_tokens && slot.n_past > 0) {
  1544. // we have to evaluate at least 1 token to generate logits.
  1545. LOG_INFO("we have to evaluate at least 1 token to generate logits", {
  1546. { "id_slot", slot.id },
  1547. { "id_task", slot.id_task }
  1548. });
  1549. slot.n_past--;
  1550. if (slot.ga_i > 0) {
  1551. slot.n_past_se--;
  1552. }
  1553. }
  1554. slot.n_prompt_tokens_processed = 0;
  1555. }
  1556. if (slot.embedding) {
  1557. // cannot fit the prompt in the current batch - will try next iter
  1558. if (batch.n_tokens + slot.n_prompt_tokens > n_batch) {
  1559. continue;
  1560. }
  1561. }
  1562. // keep only the common part
  1563. int p0 = (int) system_tokens.size() + slot.n_past;
  1564. if (!llama_kv_cache_seq_rm(ctx, slot.id + 1, p0, -1)) {
  1565. // could not partially delete (likely using a non-Transformer model)
  1566. llama_kv_cache_seq_rm(ctx, slot.id + 1, -1, -1);
  1567. p0 = (int) system_tokens.size();
  1568. if (p0 != 0) {
  1569. // copy over the system prompt when there is one
  1570. llama_kv_cache_seq_cp(ctx, 0, slot.id + 1, -1, -1);
  1571. }
  1572. // there is no common part left (except for the system prompt)
  1573. slot.n_past = 0;
  1574. slot.n_past_se = 0;
  1575. slot.ga_i = 0;
  1576. // TODO: is the system prompt ever in the sampling context?
  1577. llama_sampling_reset(slot.ctx_sampling);
  1578. }
  1579. // remove the non-common part from the cache
  1580. slot.cache_tokens.resize(slot.n_past);
  1581. LOG_INFO("kv cache rm [p0, end)", {
  1582. { "id_slot", slot.id },
  1583. { "id_task", slot.id_task },
  1584. { "p0", p0 }
  1585. });
  1586. int32_t slot_npast = slot.n_past_se > 0 ? slot.n_past_se : slot.n_past;
  1587. int32_t ga_i = slot.ga_i;
  1588. int32_t ga_n = slot.ga_n;
  1589. int32_t ga_w = slot.ga_w;
  1590. // add prompt tokens for processing in the current batch
  1591. // TODO: the self-extend stuff here is a mess - simplify and/or abstract it somehow
  1592. for (; slot.n_past < slot.n_prompt_tokens && batch.n_tokens < n_batch; ++slot.n_past) {
  1593. if (slot.ga_n != 1) {
  1594. while (slot_npast >= ga_i + ga_w) {
  1595. const int bd = (ga_w/ga_n)*(ga_n - 1);
  1596. slot_npast -= bd;
  1597. ga_i += ga_w/ga_n;
  1598. }
  1599. }
  1600. llama_batch_add(batch, prompt_tokens[slot.n_past], system_tokens.size() + slot_npast, { slot.id + 1 }, false);
  1601. if (slot.params.cache_prompt) {
  1602. slot.cache_tokens.push_back(prompt_tokens[slot.n_past]);
  1603. }
  1604. slot.n_prompt_tokens_processed++;
  1605. slot_npast++;
  1606. }
  1607. LOG_VERBOSE("prompt processing progress", {
  1608. {"id_slot", slot.id},
  1609. {"n_past", slot.n_past},
  1610. {"n_ctx", n_ctx},
  1611. {"n_tokens", batch.n_tokens},
  1612. {"progress", (float) slot.n_prompt_tokens_processed / slot.n_prompt_tokens},
  1613. });
  1614. // entire prompt has been processed - start decoding new tokens
  1615. if (slot.n_past == slot.n_prompt_tokens) {
  1616. slot.state = SLOT_STATE_PROCESSING;
  1617. slot.command = SLOT_COMMAND_NONE;
  1618. GGML_ASSERT(batch.n_tokens > 0);
  1619. // extract the logits only for the last token
  1620. batch.logits[batch.n_tokens - 1] = true;
  1621. slot.n_decoded = 0;
  1622. slot.i_batch = batch.n_tokens - 1;
  1623. LOG_VERBOSE("prompt done", {
  1624. {"id_slot", slot.id},
  1625. {"n_past", slot.n_past},
  1626. {"n_ctx", n_ctx},
  1627. {"n_tokens", batch.n_tokens},
  1628. });
  1629. }
  1630. }
  1631. if (batch.n_tokens >= n_batch) {
  1632. break;
  1633. }
  1634. }
  1635. }
  1636. if (batch.n_tokens == 0) {
  1637. LOG_VERBOSE("no tokens to decode", {});
  1638. return;
  1639. }
  1640. LOG_VERBOSE("decoding batch", {
  1641. {"n_tokens", batch.n_tokens},
  1642. });
  1643. // process the created batch of tokens
  1644. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch) {
  1645. const int32_t n_tokens = std::min(n_batch, batch.n_tokens - i);
  1646. for (auto & slot : slots) {
  1647. if (slot.ga_n != 1) {
  1648. // context extension via Self-Extend
  1649. // TODO: simplify and/or abstract this
  1650. while (slot.n_past_se >= slot.ga_i + slot.ga_w) {
  1651. const int ib = (slot.ga_n * slot.ga_i) / slot.ga_w;
  1652. const int bd = (slot.ga_w / slot.ga_n) * (slot.ga_n - 1);
  1653. const int dd = (slot.ga_w / slot.ga_n) - ib * bd - slot.ga_w;
  1654. LOG_TEE("\n");
  1655. LOG_TEE("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", slot.ga_i, slot.n_past_se, ib * bd, slot.ga_i + ib * bd, slot.n_past_se + ib * bd);
  1656. LOG_TEE("div: [%6d, %6d] / %6d -> [%6d, %6d]\n", slot.ga_i + ib * bd, slot.ga_i + ib * bd + slot.ga_w, slot.ga_n, (slot.ga_i + ib * bd) / slot.ga_n, (slot.ga_i + ib * bd + slot.ga_w) / slot.ga_n);
  1657. LOG_TEE("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", slot.ga_i + ib * bd + slot.ga_w, slot.n_past_se + ib * bd, dd, slot.ga_i + ib * bd + slot.ga_w + dd, slot.n_past_se + ib * bd + dd);
  1658. llama_kv_cache_seq_add(ctx, slot.id + 1, slot.ga_i, slot.n_past_se, ib * bd);
  1659. llama_kv_cache_seq_div(ctx, slot.id + 1, slot.ga_i + ib * bd, slot.ga_i + ib * bd + slot.ga_w, slot.ga_n);
  1660. llama_kv_cache_seq_add(ctx, slot.id + 1, slot.ga_i + ib * bd + slot.ga_w, slot.n_past_se + ib * bd, dd);
  1661. slot.n_past_se -= bd;
  1662. slot.ga_i += slot.ga_w / slot.ga_n;
  1663. LOG_TEE("\nn_past_old = %d, n_past = %d, ga_i = %d\n\n", slot.n_past_se + bd, slot.n_past_se, slot.ga_i);
  1664. }
  1665. slot.n_past_se += n_tokens;
  1666. }
  1667. }
  1668. llama_batch batch_view = {
  1669. n_tokens,
  1670. batch.token + i,
  1671. nullptr,
  1672. batch.pos + i,
  1673. batch.n_seq_id + i,
  1674. batch.seq_id + i,
  1675. batch.logits + i,
  1676. 0, 0, 0, // unused
  1677. };
  1678. const int ret = llama_decode(ctx, batch_view);
  1679. if (ret != 0) {
  1680. if (n_batch == 1 || ret < 0) {
  1681. // if you get here, it means the KV cache is full - try increasing it via the context size
  1682. LOG_TEE("%s : failed to decode the batch, n_batch = %d, ret = %d\n", __func__, n_batch, ret);
  1683. for (auto & slot : slots) {
  1684. slot.state = SLOT_STATE_PROCESSING;
  1685. slot.command = SLOT_COMMAND_NONE;
  1686. slot.release();
  1687. send_error(slot, "Input prompt is too big compared to KV size. Please try increasing KV size.");
  1688. }
  1689. break; // break loop of n_batch
  1690. }
  1691. LOG_TEE("%s : failed to find free space in the KV cache, retrying with smaller n_batch = %d\n", __func__, n_batch / 2);
  1692. // retry with half the batch size to try to find a free slot in the KV cache
  1693. n_batch /= 2;
  1694. i -= n_batch;
  1695. continue; // continue loop of n_batch
  1696. }
  1697. for (auto & slot : slots) {
  1698. if (slot.state != SLOT_STATE_PROCESSING || slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens)) {
  1699. continue; // continue loop of slots
  1700. }
  1701. // prompt evaluated for embedding
  1702. if (slot.embedding) {
  1703. send_embedding(slot, batch_view);
  1704. slot.release();
  1705. slot.i_batch = -1;
  1706. continue; // continue loop of slots
  1707. }
  1708. completion_token_output result;
  1709. const llama_token id = llama_sampling_sample(slot.ctx_sampling, ctx, NULL, slot.i_batch - i);
  1710. llama_sampling_accept(slot.ctx_sampling, ctx, id, true);
  1711. slot.n_decoded += 1;
  1712. if (slot.n_decoded == 1) {
  1713. slot.t_start_generation = ggml_time_us();
  1714. slot.t_prompt_processing = (slot.t_start_generation - slot.t_start_process_prompt) / 1e3;
  1715. metrics.on_prompt_eval(slot);
  1716. }
  1717. llama_token_data_array cur_p = { slot.ctx_sampling->cur.data(), slot.ctx_sampling->cur.size(), false };
  1718. result.tok = id;
  1719. const int32_t n_probs = slot.sparams.n_probs;
  1720. if (slot.sparams.temp <= 0 && n_probs > 0) {
  1721. // for llama_sample_token_greedy we need to sort candidates
  1722. llama_sample_softmax(ctx, &cur_p);
  1723. }
  1724. for (size_t i = 0; i < std::min(cur_p.size, (size_t) n_probs); ++i) {
  1725. result.probs.push_back({
  1726. cur_p.data[i].id,
  1727. cur_p.data[i].p
  1728. });
  1729. }
  1730. if (!process_token(result, slot)) {
  1731. slot.release();
  1732. slot.print_timings();
  1733. send_final_response(slot);
  1734. metrics.on_prediction(slot);
  1735. }
  1736. slot.i_batch = -1;
  1737. }
  1738. }
  1739. LOG_VERBOSE("run slots completed", {});
  1740. }
  1741. json model_meta() const {
  1742. return json {
  1743. {"vocab_type", llama_vocab_type (model)},
  1744. {"n_vocab", llama_n_vocab (model)},
  1745. {"n_ctx_train", llama_n_ctx_train (model)},
  1746. {"n_embd", llama_n_embd (model)},
  1747. {"n_params", llama_model_n_params(model)},
  1748. {"size", llama_model_size (model)},
  1749. };
  1750. }
  1751. };
  1752. static void server_print_usage(const char * argv0, const gpt_params & params, const server_params & sparams) {
  1753. printf("usage: %s [options]\n", argv0);
  1754. printf("\n");
  1755. printf("options:\n");
  1756. printf(" -h, --help show this help message and exit\n");
  1757. printf(" -v, --verbose verbose output (default: %s)\n", server_verbose ? "enabled" : "disabled");
  1758. printf(" -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  1759. printf(" -tb N, --threads-batch N number of threads to use during batch and prompt processing (default: same as --threads)\n");
  1760. printf(" --threads-http N number of threads in the http server pool to process requests (default: max(hardware concurrency - 1, --parallel N + 2))\n");
  1761. printf(" -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  1762. printf(" --rope-scaling {none,linear,yarn}\n");
  1763. printf(" RoPE frequency scaling method, defaults to linear unless specified by the model\n");
  1764. printf(" --rope-freq-base N RoPE base frequency (default: loaded from model)\n");
  1765. printf(" --rope-freq-scale N RoPE frequency scaling factor, expands context by a factor of 1/N\n");
  1766. printf(" --yarn-ext-factor N YaRN: extrapolation mix factor (default: 1.0, 0.0 = full interpolation)\n");
  1767. printf(" --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)\n");
  1768. printf(" --yarn-beta-slow N YaRN: high correction dim or alpha (default: %.1f)\n", params.yarn_beta_slow);
  1769. printf(" --yarn-beta-fast N YaRN: low correction dim or beta (default: %.1f)\n", params.yarn_beta_fast);
  1770. printf(" --pooling {none,mean,cls} pooling type for embeddings, use model default if unspecified\n");
  1771. printf(" -dt N, --defrag-thold N\n");
  1772. printf(" KV cache defragmentation threshold (default: %.1f, < 0 - disabled)\n", params.defrag_thold);
  1773. printf(" -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  1774. printf(" --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  1775. printf(" not recommended: doubles context memory required and no measurable increase in quality\n");
  1776. if (llama_supports_mlock()) {
  1777. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  1778. }
  1779. if (llama_supports_mmap()) {
  1780. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  1781. }
  1782. printf(" --numa TYPE attempt optimizations that help on some NUMA systems\n");
  1783. printf(" - distribute: spread execution evenly over all nodes\n");
  1784. printf(" - isolate: only spawn threads on CPUs on the node that execution started on\n");
  1785. printf(" - numactl: use the CPU map provided my numactl\n");
  1786. if (llama_supports_gpu_offload()) {
  1787. printf(" -ngl N, --n-gpu-layers N\n");
  1788. printf(" number of layers to store in VRAM\n");
  1789. printf(" -sm SPLIT_MODE, --split-mode SPLIT_MODE\n");
  1790. printf(" how to split the model across multiple GPUs, one of:\n");
  1791. printf(" - none: use one GPU only\n");
  1792. printf(" - layer (default): split layers and KV across GPUs\n");
  1793. printf(" - row: split rows across GPUs\n");
  1794. printf(" -ts SPLIT --tensor-split SPLIT\n");
  1795. printf(" fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1\n");
  1796. printf(" -mg i, --main-gpu i the GPU to use for the model (with split-mode = none),\n");
  1797. printf(" or for intermediate results and KV (with split-mode = row)\n");
  1798. }
  1799. printf(" -m FNAME, --model FNAME\n");
  1800. printf(" model path (default: %s)\n", params.model.c_str());
  1801. printf(" -a ALIAS, --alias ALIAS\n");
  1802. printf(" set an alias for the model, will be added as `model` field in completion response\n");
  1803. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  1804. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  1805. printf(" --host ip address to listen (default (default: %s)\n", sparams.hostname.c_str());
  1806. printf(" --port PORT port to listen (default (default: %d)\n", sparams.port);
  1807. printf(" --path PUBLIC_PATH path from which to serve static files (default: disabled)\n");
  1808. printf(" --api-key API_KEY optional api key to enhance server security. If set, requests must include this key for access.\n");
  1809. printf(" --api-key-file FNAME path to file containing api keys delimited by new lines. If set, requests must include one of the keys for access.\n");
  1810. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1811. printf(" --ssl-key-file FNAME path to file a PEM-encoded SSL private key\n");
  1812. printf(" --ssl-cert-file FNAME path to file a PEM-encoded SSL certificate\n");
  1813. #endif
  1814. printf(" -to N, --timeout N server read/write timeout in seconds (default: %d)\n", sparams.read_timeout);
  1815. printf(" --embeddings enable embedding vector output (default: %s)\n", params.embedding ? "enabled" : "disabled");
  1816. printf(" -np N, --parallel N number of slots for process requests (default: %d)\n", params.n_parallel);
  1817. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)\n");
  1818. printf(" -spf FNAME, --system-prompt-file FNAME\n");
  1819. printf(" set a file to load a system prompt (initial prompt of all slots), this is useful for chat applications.\n");
  1820. printf(" -ctk TYPE, --cache-type-k TYPE\n");
  1821. printf(" KV cache data type for K (default: f16)\n");
  1822. printf(" -ctv TYPE, --cache-type-v TYPE\n");
  1823. printf(" KV cache data type for V (default: f16)\n");
  1824. printf(" --log-format log output format: json or text (default: json)\n");
  1825. printf(" --log-disable disables logging to a file.\n");
  1826. printf(" --slots-endpoint-disable disables slots monitoring endpoint.\n");
  1827. printf(" --metrics enable prometheus compatible metrics endpoint (default: %s).\n", sparams.metrics_endpoint ? "enabled" : "disabled");
  1828. printf("\n");
  1829. printf(" -n, --n-predict maximum tokens to predict (default: %d)\n", params.n_predict);
  1830. printf(" --override-kv KEY=TYPE:VALUE\n");
  1831. printf(" advanced option to override model metadata by key. may be specified multiple times.\n");
  1832. printf(" types: int, float, bool. example: --override-kv tokenizer.ggml.add_bos_token=bool:false\n");
  1833. printf(" -gan N, --grp-attn-n N set the group attention factor to extend context size through self-extend(default: 1=disabled), used together with group attention width `--grp-attn-w`\n");
  1834. printf(" -gaw N, --grp-attn-w N set the group attention width to extend context size through self-extend(default: 512), used together with group attention factor `--grp-attn-n`\n");
  1835. printf(" --chat-template JINJA_TEMPLATE\n");
  1836. printf(" set custom jinja chat template (default: template taken from model's metadata)\n");
  1837. printf(" only commonly used templates are accepted:\n");
  1838. printf(" https://github.com/ggerganov/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template\n");
  1839. printf("\n");
  1840. }
  1841. static void server_params_parse(int argc, char ** argv, server_params & sparams, gpt_params & params) {
  1842. gpt_params default_params;
  1843. server_params default_sparams;
  1844. std::string arg;
  1845. bool invalid_param = false;
  1846. for (int i = 1; i < argc; i++) {
  1847. arg = argv[i];
  1848. if (arg == "--port") {
  1849. if (++i >= argc) {
  1850. invalid_param = true;
  1851. break;
  1852. }
  1853. sparams.port = std::stoi(argv[i]);
  1854. } else if (arg == "--host") {
  1855. if (++i >= argc) {
  1856. invalid_param = true;
  1857. break;
  1858. }
  1859. sparams.hostname = argv[i];
  1860. } else if (arg == "--path") {
  1861. if (++i >= argc) {
  1862. invalid_param = true;
  1863. break;
  1864. }
  1865. sparams.public_path = argv[i];
  1866. } else if (arg == "--api-key") {
  1867. if (++i >= argc) {
  1868. invalid_param = true;
  1869. break;
  1870. }
  1871. sparams.api_keys.push_back(argv[i]);
  1872. } else if (arg == "--api-key-file") {
  1873. if (++i >= argc) {
  1874. invalid_param = true;
  1875. break;
  1876. }
  1877. std::ifstream key_file(argv[i]);
  1878. if (!key_file) {
  1879. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1880. invalid_param = true;
  1881. break;
  1882. }
  1883. std::string key;
  1884. while (std::getline(key_file, key)) {
  1885. if (key.size() > 0) {
  1886. sparams.api_keys.push_back(key);
  1887. }
  1888. }
  1889. key_file.close();
  1890. }
  1891. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1892. else if (arg == "--ssl-key-file") {
  1893. if (++i >= argc) {
  1894. invalid_param = true;
  1895. break;
  1896. }
  1897. sparams.ssl_key_file = argv[i];
  1898. } else if (arg == "--ssl-cert-file") {
  1899. if (++i >= argc) {
  1900. invalid_param = true;
  1901. break;
  1902. }
  1903. sparams.ssl_cert_file = argv[i];
  1904. }
  1905. #endif
  1906. else if (arg == "--timeout" || arg == "-to") {
  1907. if (++i >= argc) {
  1908. invalid_param = true;
  1909. break;
  1910. }
  1911. sparams.read_timeout = std::stoi(argv[i]);
  1912. sparams.write_timeout = std::stoi(argv[i]);
  1913. } else if (arg == "-m" || arg == "--model") {
  1914. if (++i >= argc) {
  1915. invalid_param = true;
  1916. break;
  1917. }
  1918. params.model = argv[i];
  1919. } else if (arg == "-a" || arg == "--alias") {
  1920. if (++i >= argc) {
  1921. invalid_param = true;
  1922. break;
  1923. }
  1924. params.model_alias = argv[i];
  1925. } else if (arg == "-h" || arg == "--help") {
  1926. server_print_usage(argv[0], default_params, default_sparams);
  1927. exit(0);
  1928. } else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size") {
  1929. if (++i >= argc) {
  1930. invalid_param = true;
  1931. break;
  1932. }
  1933. params.n_ctx = std::stoi(argv[i]);
  1934. } else if (arg == "--rope-scaling") {
  1935. if (++i >= argc) {
  1936. invalid_param = true;
  1937. break;
  1938. }
  1939. std::string value(argv[i]);
  1940. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE; }
  1941. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_LINEAR; }
  1942. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_YARN; }
  1943. else { invalid_param = true; break; }
  1944. } else if (arg == "--rope-freq-base") {
  1945. if (++i >= argc) {
  1946. invalid_param = true;
  1947. break;
  1948. }
  1949. params.rope_freq_base = std::stof(argv[i]);
  1950. } else if (arg == "--rope-freq-scale") {
  1951. if (++i >= argc) {
  1952. invalid_param = true;
  1953. break;
  1954. }
  1955. params.rope_freq_scale = std::stof(argv[i]);
  1956. } else if (arg == "--yarn-ext-factor") {
  1957. if (++i >= argc) {
  1958. invalid_param = true;
  1959. break;
  1960. }
  1961. params.yarn_ext_factor = std::stof(argv[i]);
  1962. }
  1963. else if (arg == "--yarn-attn-factor") {
  1964. if (++i >= argc) {
  1965. invalid_param = true;
  1966. break;
  1967. }
  1968. params.yarn_attn_factor = std::stof(argv[i]);
  1969. } else if (arg == "--yarn-beta-fast") {
  1970. if (++i >= argc) {
  1971. invalid_param = true;
  1972. break;
  1973. }
  1974. params.yarn_beta_fast = std::stof(argv[i]);
  1975. } else if (arg == "--yarn-beta-slow") {
  1976. if (++i >= argc) {
  1977. invalid_param = true;
  1978. break;
  1979. }
  1980. params.yarn_beta_slow = std::stof(argv[i]);
  1981. } else if (arg == "--pooling") {
  1982. if (++i >= argc) {
  1983. invalid_param = true;
  1984. break;
  1985. }
  1986. std::string value(argv[i]);
  1987. /**/ if (value == "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
  1988. else if (value == "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
  1989. else if (value == "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
  1990. else { invalid_param = true; break; }
  1991. } else if (arg == "--defrag-thold" || arg == "-dt") {
  1992. if (++i >= argc) {
  1993. invalid_param = true;
  1994. break;
  1995. }
  1996. params.defrag_thold = std::stof(argv[i]);
  1997. } else if (arg == "--threads" || arg == "-t") {
  1998. if (++i >= argc)
  1999. {
  2000. invalid_param = true;
  2001. break;
  2002. }
  2003. params.n_threads = std::stoi(argv[i]);
  2004. } else if (arg == "--grp-attn-n" || arg == "-gan") {
  2005. if (++i >= argc) {
  2006. invalid_param = true;
  2007. break;
  2008. }
  2009. params.grp_attn_n = std::stoi(argv[i]);
  2010. } else if (arg == "--grp-attn-w" || arg == "-gaw") {
  2011. if (++i >= argc) {
  2012. invalid_param = true;
  2013. break;
  2014. }
  2015. params.grp_attn_w = std::stoi(argv[i]);
  2016. } else if (arg == "--threads-batch" || arg == "-tb") {
  2017. if (++i >= argc) {
  2018. invalid_param = true;
  2019. break;
  2020. }
  2021. params.n_threads_batch = std::stoi(argv[i]);
  2022. } else if (arg == "--threads-http") {
  2023. if (++i >= argc) {
  2024. invalid_param = true;
  2025. break;
  2026. }
  2027. sparams.n_threads_http = std::stoi(argv[i]);
  2028. } else if (arg == "-b" || arg == "--batch-size") {
  2029. if (++i >= argc) {
  2030. invalid_param = true;
  2031. break;
  2032. }
  2033. params.n_batch = std::stoi(argv[i]);
  2034. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  2035. if (++i >= argc) {
  2036. invalid_param = true;
  2037. break;
  2038. }
  2039. if (llama_supports_gpu_offload()) {
  2040. params.n_gpu_layers = std::stoi(argv[i]);
  2041. } else {
  2042. LOG_WARNING(
  2043. "Not compiled with GPU offload support, --n-gpu-layers option will be ignored. "
  2044. "See main README.md for information on enabling GPU BLAS support",
  2045. {{"n_gpu_layers", params.n_gpu_layers}});
  2046. }
  2047. } else if (arg == "--split-mode" || arg == "-sm") {
  2048. if (++i >= argc) {
  2049. invalid_param = true;
  2050. break;
  2051. }
  2052. std::string arg_next = argv[i];
  2053. if (arg_next == "none") {
  2054. params.split_mode = LLAMA_SPLIT_MODE_NONE;
  2055. } else if (arg_next == "layer") {
  2056. params.split_mode = LLAMA_SPLIT_MODE_LAYER;
  2057. } else if (arg_next == "row") {
  2058. params.split_mode = LLAMA_SPLIT_MODE_ROW;
  2059. } else {
  2060. invalid_param = true;
  2061. break;
  2062. }
  2063. #ifndef GGML_USE_CUBLAS
  2064. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. Setting the split mode has no effect.\n");
  2065. #endif // GGML_USE_CUBLAS
  2066. } else if (arg == "--tensor-split" || arg == "-ts") {
  2067. if (++i >= argc) {
  2068. invalid_param = true;
  2069. break;
  2070. }
  2071. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL)
  2072. std::string arg_next = argv[i];
  2073. // split string by , and /
  2074. const std::regex regex{R"([,/]+)"};
  2075. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  2076. std::vector<std::string> split_arg{it, {}};
  2077. GGML_ASSERT(split_arg.size() <= llama_max_devices());
  2078. for (size_t i_device = 0; i_device < llama_max_devices(); ++i_device) {
  2079. if (i_device < split_arg.size()) {
  2080. params.tensor_split[i_device] = std::stof(split_arg[i_device]);
  2081. } else {
  2082. params.tensor_split[i_device] = 0.0f;
  2083. }
  2084. }
  2085. #else
  2086. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n", {});
  2087. #endif // GGML_USE_CUBLAS
  2088. } else if (arg == "--main-gpu" || arg == "-mg") {
  2089. if (++i >= argc) {
  2090. invalid_param = true;
  2091. break;
  2092. }
  2093. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL)
  2094. params.main_gpu = std::stoi(argv[i]);
  2095. #else
  2096. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.", {});
  2097. #endif
  2098. } else if (arg == "--lora") {
  2099. if (++i >= argc) {
  2100. invalid_param = true;
  2101. break;
  2102. }
  2103. params.lora_adapter.emplace_back(argv[i], 1.0f);
  2104. params.use_mmap = false;
  2105. } else if (arg == "--lora-scaled") {
  2106. if (++i >= argc) {
  2107. invalid_param = true;
  2108. break;
  2109. }
  2110. const char * lora_adapter = argv[i];
  2111. if (++i >= argc) {
  2112. invalid_param = true;
  2113. break;
  2114. }
  2115. params.lora_adapter.emplace_back(lora_adapter, std::stof(argv[i]));
  2116. params.use_mmap = false;
  2117. } else if (arg == "--lora-base") {
  2118. if (++i >= argc) {
  2119. invalid_param = true;
  2120. break;
  2121. }
  2122. params.lora_base = argv[i];
  2123. } else if (arg == "-v" || arg == "--verbose") {
  2124. #if SERVER_VERBOSE != 1
  2125. LOG_WARNING("server.cpp is not built with verbose logging.", {});
  2126. #else
  2127. server_verbose = true;
  2128. #endif
  2129. } else if (arg == "--mlock") {
  2130. params.use_mlock = true;
  2131. } else if (arg == "--no-mmap") {
  2132. params.use_mmap = false;
  2133. } else if (arg == "--numa") {
  2134. if (++i >= argc) {
  2135. invalid_param = true;
  2136. break;
  2137. } else {
  2138. std::string value(argv[i]);
  2139. /**/ if (value == "distribute" || value == "" ) { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
  2140. else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
  2141. else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
  2142. else { invalid_param = true; break; }
  2143. }
  2144. } else if (arg == "--embedding" || arg == "--embeddings") {
  2145. params.embedding = true;
  2146. } else if (arg == "-cb" || arg == "--cont-batching") {
  2147. params.cont_batching = true;
  2148. } else if (arg == "-np" || arg == "--parallel") {
  2149. if (++i >= argc) {
  2150. invalid_param = true;
  2151. break;
  2152. }
  2153. params.n_parallel = std::stoi(argv[i]);
  2154. } else if (arg == "-n" || arg == "--n-predict") {
  2155. if (++i >= argc) {
  2156. invalid_param = true;
  2157. break;
  2158. }
  2159. params.n_predict = std::stoi(argv[i]);
  2160. } else if (arg == "-spf" || arg == "--system-prompt-file") {
  2161. if (++i >= argc) {
  2162. invalid_param = true;
  2163. break;
  2164. }
  2165. std::ifstream file(argv[i]);
  2166. if (!file) {
  2167. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  2168. invalid_param = true;
  2169. break;
  2170. }
  2171. std::string system_prompt;
  2172. std::copy(
  2173. std::istreambuf_iterator<char>(file),
  2174. std::istreambuf_iterator<char>(),
  2175. std::back_inserter(system_prompt)
  2176. );
  2177. sparams.system_prompt = system_prompt;
  2178. } else if (arg == "-ctk" || arg == "--cache-type-k") {
  2179. params.cache_type_k = argv[++i];
  2180. } else if (arg == "-ctv" || arg == "--cache-type-v") {
  2181. params.cache_type_v = argv[++i];
  2182. } else if (arg == "--log-format") {
  2183. if (++i >= argc) {
  2184. invalid_param = true;
  2185. break;
  2186. }
  2187. if (std::strcmp(argv[i], "json") == 0) {
  2188. server_log_json = true;
  2189. } else if (std::strcmp(argv[i], "text") == 0) {
  2190. server_log_json = false;
  2191. } else {
  2192. invalid_param = true;
  2193. break;
  2194. }
  2195. } else if (arg == "--log-disable") {
  2196. log_set_target(stdout);
  2197. LOG_INFO("logging to file is disabled.", {});
  2198. } else if (arg == "--slots-endpoint-disable") {
  2199. sparams.slots_endpoint = false;
  2200. } else if (arg == "--metrics") {
  2201. sparams.metrics_endpoint = true;
  2202. } else if (arg == "--chat-template") {
  2203. if (++i >= argc) {
  2204. invalid_param = true;
  2205. break;
  2206. }
  2207. if (!verify_custom_template(argv[i])) {
  2208. fprintf(stderr, "error: the supplied chat template is not supported: %s\n", argv[i]);
  2209. fprintf(stderr, "note: llama.cpp does not use jinja parser, we only support commonly used templates\n");
  2210. invalid_param = true;
  2211. break;
  2212. }
  2213. sparams.chat_template = argv[i];
  2214. } else if (arg == "--override-kv") {
  2215. if (++i >= argc) {
  2216. invalid_param = true;
  2217. break;
  2218. }
  2219. char * sep = strchr(argv[i], '=');
  2220. if (sep == nullptr || sep - argv[i] >= 128) {
  2221. fprintf(stderr, "error: Malformed KV override: %s\n", argv[i]);
  2222. invalid_param = true;
  2223. break;
  2224. }
  2225. struct llama_model_kv_override kvo;
  2226. std::strncpy(kvo.key, argv[i], sep - argv[i]);
  2227. kvo.key[sep - argv[i]] = 0;
  2228. sep++;
  2229. if (strncmp(sep, "int:", 4) == 0) {
  2230. sep += 4;
  2231. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  2232. kvo.int_value = std::atol(sep);
  2233. } else if (strncmp(sep, "float:", 6) == 0) {
  2234. sep += 6;
  2235. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
  2236. kvo.float_value = std::atof(sep);
  2237. } else if (strncmp(sep, "bool:", 5) == 0) {
  2238. sep += 5;
  2239. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
  2240. if (std::strcmp(sep, "true") == 0) {
  2241. kvo.bool_value = true;
  2242. } else if (std::strcmp(sep, "false") == 0) {
  2243. kvo.bool_value = false;
  2244. } else {
  2245. fprintf(stderr, "error: Invalid boolean value for KV override: %s\n", argv[i]);
  2246. invalid_param = true;
  2247. break;
  2248. }
  2249. } else {
  2250. fprintf(stderr, "error: Invalid type for KV override: %s\n", argv[i]);
  2251. invalid_param = true;
  2252. break;
  2253. }
  2254. params.kv_overrides.push_back(kvo);
  2255. } else {
  2256. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  2257. server_print_usage(argv[0], default_params, default_sparams);
  2258. exit(1);
  2259. }
  2260. }
  2261. if (!params.kv_overrides.empty()) {
  2262. params.kv_overrides.emplace_back();
  2263. params.kv_overrides.back().key[0] = 0;
  2264. }
  2265. if (invalid_param) {
  2266. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  2267. server_print_usage(argv[0], default_params, default_sparams);
  2268. exit(1);
  2269. }
  2270. }
  2271. static void log_server_request(const httplib::Request & req, const httplib::Response & res) {
  2272. // skip GH copilot requests when using default port
  2273. if (req.path == "/v1/health" || req.path == "/v1/completions") {
  2274. return;
  2275. }
  2276. LOG_INFO("request", {
  2277. {"remote_addr", req.remote_addr},
  2278. {"remote_port", req.remote_port},
  2279. {"status", res.status},
  2280. {"method", req.method},
  2281. {"path", req.path},
  2282. {"params", req.params},
  2283. });
  2284. LOG_VERBOSE("request", {
  2285. {"request", req.body},
  2286. {"response", res.body},
  2287. });
  2288. }
  2289. std::function<void(int)> shutdown_handler;
  2290. std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
  2291. inline void signal_handler(int signal) {
  2292. if (is_terminating.test_and_set()) {
  2293. // in case it hangs, we can force terminate the server by hitting Ctrl+C twice
  2294. // this is for better developer experience, we can remove when the server is stable enough
  2295. fprintf(stderr, "Received second interrupt, terminating immediately.\n");
  2296. exit(1);
  2297. }
  2298. shutdown_handler(signal);
  2299. }
  2300. int main(int argc, char ** argv) {
  2301. #if SERVER_VERBOSE != 1
  2302. log_disable();
  2303. #endif
  2304. // own arguments required by this example
  2305. gpt_params params;
  2306. server_params sparams;
  2307. // struct that contains llama context and inference
  2308. server_context ctx_server;
  2309. server_params_parse(argc, argv, sparams, params);
  2310. if (!sparams.system_prompt.empty()) {
  2311. ctx_server.system_prompt_set(json::parse(sparams.system_prompt));
  2312. }
  2313. if (params.model_alias == "unknown") {
  2314. params.model_alias = params.model;
  2315. }
  2316. llama_backend_init();
  2317. llama_numa_init(params.numa);
  2318. LOG_INFO("build info", {
  2319. {"build", LLAMA_BUILD_NUMBER},
  2320. {"commit", LLAMA_COMMIT}
  2321. });
  2322. LOG_INFO("system info", {
  2323. {"n_threads", params.n_threads},
  2324. {"n_threads_batch", params.n_threads_batch},
  2325. {"total_threads", std::thread::hardware_concurrency()},
  2326. {"system_info", llama_print_system_info()},
  2327. });
  2328. std::unique_ptr<httplib::Server> svr;
  2329. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2330. if (sparams.ssl_key_file != "" && sparams.ssl_cert_file != "") {
  2331. LOG_INFO("Running with SSL", {{"key", sparams.ssl_key_file}, {"cert", sparams.ssl_cert_file}});
  2332. svr.reset(
  2333. new httplib::SSLServer(sparams.ssl_cert_file.c_str(), sparams.ssl_key_file.c_str())
  2334. );
  2335. } else {
  2336. LOG_INFO("Running without SSL", {});
  2337. svr.reset(new httplib::Server());
  2338. }
  2339. #else
  2340. svr.reset(new httplib::Server());
  2341. #endif
  2342. std::atomic<server_state> state{SERVER_STATE_LOADING_MODEL};
  2343. svr->set_default_headers({{"Server", "llama.cpp"}});
  2344. // CORS preflight
  2345. svr->Options(R"(.*)", [](const httplib::Request & req, httplib::Response & res) {
  2346. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2347. res.set_header("Access-Control-Allow-Credentials", "true");
  2348. res.set_header("Access-Control-Allow-Methods", "POST");
  2349. res.set_header("Access-Control-Allow-Headers", "*");
  2350. return res.set_content("", "application/json; charset=utf-8");
  2351. });
  2352. svr->set_logger(log_server_request);
  2353. auto res_error = [](httplib::Response & res, json error_data) {
  2354. json final_response {{"error", error_data}};
  2355. res.set_content(final_response.dump(), "application/json; charset=utf-8");
  2356. res.status = json_value(error_data, "code", 500);
  2357. };
  2358. svr->set_exception_handler([&res_error](const httplib::Request &, httplib::Response & res, std::exception_ptr ep) {
  2359. std::string message;
  2360. try {
  2361. std::rethrow_exception(std::move(ep));
  2362. } catch (std::exception & e) {
  2363. message = e.what();
  2364. } catch (...) {
  2365. message = "Unknown Exception";
  2366. }
  2367. json formatted_error = format_error_response(message, ERROR_TYPE_SERVER);
  2368. LOG_VERBOSE("Got exception", formatted_error);
  2369. res_error(res, formatted_error);
  2370. });
  2371. svr->set_error_handler([&res_error](const httplib::Request &, httplib::Response & res) {
  2372. if (res.status == 404) {
  2373. res_error(res, format_error_response("File Not Found", ERROR_TYPE_NOT_FOUND));
  2374. }
  2375. // for other error codes, we skip processing here because it's already done by res_error()
  2376. });
  2377. // set timeouts and change hostname and port
  2378. svr->set_read_timeout (sparams.read_timeout);
  2379. svr->set_write_timeout(sparams.write_timeout);
  2380. if (!svr->bind_to_port(sparams.hostname, sparams.port)) {
  2381. fprintf(stderr, "\ncouldn't bind to server socket: hostname=%s port=%d\n\n", sparams.hostname.c_str(), sparams.port);
  2382. return 1;
  2383. }
  2384. std::unordered_map<std::string, std::string> log_data;
  2385. log_data["hostname"] = sparams.hostname;
  2386. log_data["port"] = std::to_string(sparams.port);
  2387. if (sparams.api_keys.size() == 1) {
  2388. auto key = sparams.api_keys[0];
  2389. log_data["api_key"] = "api_key: ****" + key.substr(std::max((int)(key.length() - 4), 0));
  2390. } else if (sparams.api_keys.size() > 1) {
  2391. log_data["api_key"] = "api_key: " + std::to_string(sparams.api_keys.size()) + " keys loaded";
  2392. }
  2393. // load the model
  2394. if (!ctx_server.load_model(params)) {
  2395. state.store(SERVER_STATE_ERROR);
  2396. return 1;
  2397. } else {
  2398. ctx_server.init();
  2399. state.store(SERVER_STATE_READY);
  2400. }
  2401. LOG_INFO("model loaded", {});
  2402. const auto model_meta = ctx_server.model_meta();
  2403. // if a custom chat template is not supplied, we will use the one that comes with the model (if any)
  2404. if (sparams.chat_template.empty()) {
  2405. if (!ctx_server.validate_model_chat_template()) {
  2406. LOG_ERROR("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", {});
  2407. sparams.chat_template = "chatml";
  2408. }
  2409. }
  2410. // print sample chat example to make it clear which template is used
  2411. {
  2412. json chat;
  2413. chat.push_back({{"role", "system"}, {"content", "You are a helpful assistant"}});
  2414. chat.push_back({{"role", "user"}, {"content", "Hello"}});
  2415. chat.push_back({{"role", "assistant"}, {"content", "Hi there"}});
  2416. chat.push_back({{"role", "user"}, {"content", "How are you?"}});
  2417. const std::string chat_example = format_chat(ctx_server.model, sparams.chat_template, chat);
  2418. LOG_INFO("chat template", {
  2419. {"chat_example", chat_example},
  2420. {"built_in", sparams.chat_template.empty()},
  2421. });
  2422. }
  2423. //
  2424. // Middlewares
  2425. //
  2426. auto middleware_validate_api_key = [&sparams, &res_error](const httplib::Request & req, httplib::Response & res) {
  2427. // TODO: should we apply API key to all endpoints, including "/health" and "/models"?
  2428. static const std::set<std::string> protected_endpoints = {
  2429. "/props",
  2430. "/completion",
  2431. "/completions",
  2432. "/v1/completions",
  2433. "/chat/completions",
  2434. "/v1/chat/completions",
  2435. "/infill",
  2436. "/tokenize",
  2437. "/detokenize",
  2438. "/embedding",
  2439. "/embeddings",
  2440. "/v1/embeddings",
  2441. };
  2442. // If API key is not set, skip validation
  2443. if (sparams.api_keys.empty()) {
  2444. return true;
  2445. }
  2446. // If path is not in protected_endpoints list, skip validation
  2447. if (protected_endpoints.find(req.path) == protected_endpoints.end()) {
  2448. return true;
  2449. }
  2450. // Check for API key in the header
  2451. auto auth_header = req.get_header_value("Authorization");
  2452. std::string prefix = "Bearer ";
  2453. if (auth_header.substr(0, prefix.size()) == prefix) {
  2454. std::string received_api_key = auth_header.substr(prefix.size());
  2455. if (std::find(sparams.api_keys.begin(), sparams.api_keys.end(), received_api_key) != sparams.api_keys.end()) {
  2456. return true; // API key is valid
  2457. }
  2458. }
  2459. // API key is invalid or not provided
  2460. // TODO: make another middleware for CORS related logic
  2461. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2462. res_error(res, format_error_response("Invalid API Key", ERROR_TYPE_AUTHENTICATION));
  2463. LOG_WARNING("Unauthorized: Invalid API Key", {});
  2464. return false;
  2465. };
  2466. // register server middlewares
  2467. svr->set_pre_routing_handler([&middleware_validate_api_key](const httplib::Request & req, httplib::Response & res) {
  2468. if (!middleware_validate_api_key(req, res)) {
  2469. return httplib::Server::HandlerResponse::Handled;
  2470. }
  2471. return httplib::Server::HandlerResponse::Unhandled;
  2472. });
  2473. //
  2474. // Route handlers (or controllers)
  2475. //
  2476. const auto handle_health = [&](const httplib::Request & req, httplib::Response & res) {
  2477. server_state current_state = state.load();
  2478. switch (current_state) {
  2479. case SERVER_STATE_READY:
  2480. {
  2481. // request slots data using task queue
  2482. server_task task;
  2483. task.id = ctx_server.queue_tasks.get_new_id();
  2484. task.type = SERVER_TASK_TYPE_METRICS;
  2485. task.id_target = -1;
  2486. ctx_server.queue_results.add_waiting_task_id(task.id);
  2487. ctx_server.queue_tasks.post(task);
  2488. // get the result
  2489. server_task_result result = ctx_server.queue_results.recv(task.id);
  2490. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2491. const int n_idle_slots = result.data["idle"];
  2492. const int n_processing_slots = result.data["processing"];
  2493. json health = {
  2494. {"status", "ok"},
  2495. {"slots_idle", n_idle_slots},
  2496. {"slots_processing", n_processing_slots}
  2497. };
  2498. res.status = 200; // HTTP OK
  2499. if (sparams.slots_endpoint && req.has_param("include_slots")) {
  2500. health["slots"] = result.data["slots"];
  2501. }
  2502. if (n_idle_slots == 0) {
  2503. health["status"] = "no slot available";
  2504. if (req.has_param("fail_on_no_slot")) {
  2505. res.status = 503; // HTTP Service Unavailable
  2506. }
  2507. }
  2508. res.set_content(health.dump(), "application/json");
  2509. break;
  2510. }
  2511. case SERVER_STATE_LOADING_MODEL:
  2512. {
  2513. res_error(res, format_error_response("Loading model", ERROR_TYPE_UNAVAILABLE));
  2514. } break;
  2515. case SERVER_STATE_ERROR:
  2516. {
  2517. res_error(res, format_error_response("Model failed to load", ERROR_TYPE_SERVER));
  2518. } break;
  2519. }
  2520. };
  2521. const auto handle_slots = [&](const httplib::Request &, httplib::Response & res) {
  2522. if (!sparams.slots_endpoint) {
  2523. res_error(res, format_error_response("This server does not support slots endpoint.", ERROR_TYPE_NOT_SUPPORTED));
  2524. return;
  2525. }
  2526. // request slots data using task queue
  2527. server_task task;
  2528. task.id = ctx_server.queue_tasks.get_new_id();
  2529. task.id_multi = -1;
  2530. task.id_target = -1;
  2531. task.type = SERVER_TASK_TYPE_METRICS;
  2532. ctx_server.queue_results.add_waiting_task_id(task.id);
  2533. ctx_server.queue_tasks.post(task);
  2534. // get the result
  2535. server_task_result result = ctx_server.queue_results.recv(task.id);
  2536. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2537. res.set_content(result.data["slots"].dump(), "application/json");
  2538. res.status = 200; // HTTP OK
  2539. };
  2540. const auto handle_metrics = [&](const httplib::Request &, httplib::Response & res) {
  2541. if (!sparams.metrics_endpoint) {
  2542. res_error(res, format_error_response("This server does not support metrics endpoint.", ERROR_TYPE_NOT_SUPPORTED));
  2543. return;
  2544. }
  2545. // request slots data using task queue
  2546. server_task task;
  2547. task.id = ctx_server.queue_tasks.get_new_id();
  2548. task.id_multi = -1;
  2549. task.id_target = -1;
  2550. task.type = SERVER_TASK_TYPE_METRICS;
  2551. task.data.push_back({{"reset_bucket", true}});
  2552. ctx_server.queue_results.add_waiting_task_id(task.id);
  2553. ctx_server.queue_tasks.post(task);
  2554. // get the result
  2555. server_task_result result = ctx_server.queue_results.recv(task.id);
  2556. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2557. json data = result.data;
  2558. const uint64_t n_prompt_tokens_processed = data["n_prompt_tokens_processed"];
  2559. const uint64_t t_prompt_processing = data["t_prompt_processing"];
  2560. const uint64_t n_tokens_predicted = data["n_tokens_predicted"];
  2561. const uint64_t t_tokens_generation = data["t_tokens_generation"];
  2562. const int32_t kv_cache_used_cells = data["kv_cache_used_cells"];
  2563. // metrics definition: https://prometheus.io/docs/practices/naming/#metric-names
  2564. json all_metrics_def = json {
  2565. {"counter", {{
  2566. {"name", "prompt_tokens_total"},
  2567. {"help", "Number of prompt tokens processed."},
  2568. {"value", (uint64_t) data["n_prompt_tokens_processed_total"]}
  2569. }, {
  2570. {"name", "prompt_seconds_total"},
  2571. {"help", "Prompt process time"},
  2572. {"value", (uint64_t) data["t_prompt_processing_total"] / 1.e3}
  2573. }, {
  2574. {"name", "tokens_predicted_total"},
  2575. {"help", "Number of generation tokens processed."},
  2576. {"value", (uint64_t) data["n_tokens_predicted_total"]}
  2577. }, {
  2578. {"name", "tokens_predicted_seconds_total"},
  2579. {"help", "Predict process time"},
  2580. {"value", (uint64_t) data["t_tokens_generation_total"] / 1.e3}
  2581. }}},
  2582. {"gauge", {{
  2583. {"name", "prompt_tokens_seconds"},
  2584. {"help", "Average prompt throughput in tokens/s."},
  2585. {"value", n_prompt_tokens_processed ? 1.e3 / t_prompt_processing * n_prompt_tokens_processed : 0.}
  2586. },{
  2587. {"name", "predicted_tokens_seconds"},
  2588. {"help", "Average generation throughput in tokens/s."},
  2589. {"value", n_tokens_predicted ? 1.e3 / t_tokens_generation * n_tokens_predicted : 0.}
  2590. },{
  2591. {"name", "kv_cache_usage_ratio"},
  2592. {"help", "KV-cache usage. 1 means 100 percent usage."},
  2593. {"value", 1. * kv_cache_used_cells / params.n_ctx}
  2594. },{
  2595. {"name", "kv_cache_tokens"},
  2596. {"help", "KV-cache tokens."},
  2597. {"value", (uint64_t) data["kv_cache_tokens_count"]}
  2598. },{
  2599. {"name", "requests_processing"},
  2600. {"help", "Number of request processing."},
  2601. {"value", (uint64_t) data["processing"]}
  2602. },{
  2603. {"name", "requests_deferred"},
  2604. {"help", "Number of request deferred."},
  2605. {"value", (uint64_t) data["deferred"]}
  2606. }}}
  2607. };
  2608. std::stringstream prometheus;
  2609. for (const auto & el : all_metrics_def.items()) {
  2610. const auto & type = el.key();
  2611. const auto & metrics_def = el.value();
  2612. for (const auto & metric_def : metrics_def) {
  2613. const std::string name = metric_def["name"];
  2614. const std::string help = metric_def["help"];
  2615. auto value = json_value(metric_def, "value", 0.);
  2616. prometheus << "# HELP llamacpp:" << name << " " << help << "\n"
  2617. << "# TYPE llamacpp:" << name << " " << type << "\n"
  2618. << "llamacpp:" << name << " " << value << "\n";
  2619. }
  2620. }
  2621. const int64_t t_start = data["t_start"];
  2622. res.set_header("Process-Start-Time-Unix", std::to_string(t_start));
  2623. res.set_content(prometheus.str(), "text/plain; version=0.0.4");
  2624. res.status = 200; // HTTP OK
  2625. };
  2626. const auto handle_props = [&ctx_server](const httplib::Request & req, httplib::Response & res) {
  2627. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2628. json data = {
  2629. { "user_name", ctx_server.name_user.c_str() },
  2630. { "assistant_name", ctx_server.name_assistant.c_str() },
  2631. { "default_generation_settings", ctx_server.default_generation_settings_for_props },
  2632. { "total_slots", ctx_server.params.n_parallel }
  2633. };
  2634. res.set_content(data.dump(), "application/json; charset=utf-8");
  2635. };
  2636. const auto handle_completions = [&ctx_server, &res_error](const httplib::Request & req, httplib::Response & res) {
  2637. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2638. json data = json::parse(req.body);
  2639. const int id_task = ctx_server.queue_tasks.get_new_id();
  2640. ctx_server.queue_results.add_waiting_task_id(id_task);
  2641. ctx_server.request_completion(id_task, -1, data, false, false);
  2642. if (!json_value(data, "stream", false)) {
  2643. server_task_result result = ctx_server.queue_results.recv(id_task);
  2644. if (!result.error && result.stop) {
  2645. res.set_content(result.data.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  2646. } else {
  2647. res_error(res, result.data);
  2648. }
  2649. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2650. } else {
  2651. const auto chunked_content_provider = [id_task, &ctx_server](size_t, httplib::DataSink & sink) {
  2652. while (true) {
  2653. server_task_result result = ctx_server.queue_results.recv(id_task);
  2654. if (!result.error) {
  2655. const std::string str =
  2656. "data: " +
  2657. result.data.dump(-1, ' ', false, json::error_handler_t::replace) +
  2658. "\n\n";
  2659. LOG_VERBOSE("data stream", {
  2660. { "to_send", str }
  2661. });
  2662. if (!sink.write(str.c_str(), str.size())) {
  2663. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2664. return false;
  2665. }
  2666. if (result.stop) {
  2667. break;
  2668. }
  2669. } else {
  2670. const std::string str =
  2671. "error: " +
  2672. result.data.dump(-1, ' ', false, json::error_handler_t::replace) +
  2673. "\n\n";
  2674. LOG_VERBOSE("data stream", {
  2675. { "to_send", str }
  2676. });
  2677. if (!sink.write(str.c_str(), str.size())) {
  2678. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2679. return false;
  2680. }
  2681. break;
  2682. }
  2683. }
  2684. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2685. sink.done();
  2686. return true;
  2687. };
  2688. auto on_complete = [id_task, &ctx_server] (bool) {
  2689. // cancel
  2690. ctx_server.request_cancel(id_task);
  2691. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2692. };
  2693. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2694. }
  2695. };
  2696. const auto handle_models = [&params, &model_meta](const httplib::Request & req, httplib::Response & res) {
  2697. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2698. json models = {
  2699. {"object", "list"},
  2700. {"data", {
  2701. {
  2702. {"id", params.model_alias},
  2703. {"object", "model"},
  2704. {"created", std::time(0)},
  2705. {"owned_by", "llamacpp"},
  2706. {"meta", model_meta}
  2707. },
  2708. }}
  2709. };
  2710. res.set_content(models.dump(), "application/json; charset=utf-8");
  2711. };
  2712. const auto handle_chat_completions = [&ctx_server, &sparams, &res_error](const httplib::Request & req, httplib::Response & res) {
  2713. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2714. json data = oaicompat_completion_params_parse(ctx_server.model, json::parse(req.body), sparams.chat_template);
  2715. const int id_task = ctx_server.queue_tasks.get_new_id();
  2716. ctx_server.queue_results.add_waiting_task_id(id_task);
  2717. ctx_server.request_completion(id_task, -1, data, false, false);
  2718. const auto completion_id = gen_chatcmplid();
  2719. if (!json_value(data, "stream", false)) {
  2720. server_task_result result = ctx_server.queue_results.recv(id_task);
  2721. if (!result.error && result.stop) {
  2722. json result_oai = format_final_response_oaicompat(data, result.data, completion_id);
  2723. res.set_content(result_oai.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  2724. } else {
  2725. res_error(res, result.data);
  2726. }
  2727. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2728. } else {
  2729. const auto chunked_content_provider = [id_task, &ctx_server, completion_id](size_t, httplib::DataSink & sink) {
  2730. while (true) {
  2731. server_task_result result = ctx_server.queue_results.recv(id_task);
  2732. if (!result.error) {
  2733. std::vector<json> result_array = format_partial_response_oaicompat(result.data, completion_id);
  2734. for (auto it = result_array.begin(); it != result_array.end(); ++it) {
  2735. if (!it->empty()) {
  2736. const std::string str =
  2737. "data: " +
  2738. it->dump(-1, ' ', false, json::error_handler_t::replace) +
  2739. "\n\n";
  2740. LOG_VERBOSE("data stream", {{"to_send", str}});
  2741. if (!sink.write(str.c_str(), str.size())) {
  2742. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2743. return false;
  2744. }
  2745. }
  2746. }
  2747. if (result.stop) {
  2748. break;
  2749. }
  2750. } else {
  2751. const std::string str =
  2752. "error: " +
  2753. result.data.dump(-1, ' ', false, json::error_handler_t::replace) +
  2754. "\n\n";
  2755. LOG_VERBOSE("data stream", {{"to_send", str}});
  2756. if (!sink.write(str.c_str(), str.size())) {
  2757. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2758. return false;
  2759. }
  2760. break;
  2761. }
  2762. }
  2763. sink.done();
  2764. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2765. return true;
  2766. };
  2767. auto on_complete = [id_task, &ctx_server](bool) {
  2768. // cancel request
  2769. ctx_server.request_cancel(id_task);
  2770. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2771. };
  2772. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2773. }
  2774. };
  2775. const auto handle_infill = [&ctx_server, &res_error](const httplib::Request & req, httplib::Response & res) {
  2776. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2777. json data = json::parse(req.body);
  2778. const int id_task = ctx_server.queue_tasks.get_new_id();
  2779. ctx_server.queue_results.add_waiting_task_id(id_task);
  2780. ctx_server.request_completion(id_task, -1, data, true, false);
  2781. if (!json_value(data, "stream", false)) {
  2782. server_task_result result = ctx_server.queue_results.recv(id_task);
  2783. if (!result.error && result.stop) {
  2784. res.set_content(result.data.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  2785. } else {
  2786. res_error(res, result.data);
  2787. }
  2788. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2789. } else {
  2790. const auto chunked_content_provider = [id_task, &ctx_server](size_t, httplib::DataSink & sink) {
  2791. while (true) {
  2792. server_task_result result = ctx_server.queue_results.recv(id_task);
  2793. if (!result.error) {
  2794. const std::string str =
  2795. "data: " +
  2796. result.data.dump(-1, ' ', false, json::error_handler_t::replace) +
  2797. "\n\n";
  2798. LOG_VERBOSE("data stream", {
  2799. { "to_send", str }
  2800. });
  2801. if (!sink.write(str.c_str(), str.size())) {
  2802. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2803. return false;
  2804. }
  2805. if (result.stop) {
  2806. break;
  2807. }
  2808. } else {
  2809. break;
  2810. }
  2811. }
  2812. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2813. sink.done();
  2814. return true;
  2815. };
  2816. auto on_complete = [id_task, &ctx_server] (bool) {
  2817. ctx_server.request_cancel(id_task);
  2818. };
  2819. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2820. }
  2821. };
  2822. const auto handle_tokenize = [&ctx_server](const httplib::Request & req, httplib::Response & res) {
  2823. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2824. const json body = json::parse(req.body);
  2825. std::vector<llama_token> tokens;
  2826. if (body.count("content") != 0) {
  2827. tokens = ctx_server.tokenize(body["content"], false);
  2828. }
  2829. const json data = format_tokenizer_response(tokens);
  2830. return res.set_content(data.dump(), "application/json; charset=utf-8");
  2831. };
  2832. const auto handle_detokenize = [&ctx_server](const httplib::Request & req, httplib::Response & res) {
  2833. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2834. const json body = json::parse(req.body);
  2835. std::string content;
  2836. if (body.count("tokens") != 0) {
  2837. const std::vector<llama_token> tokens = body["tokens"];
  2838. content = tokens_to_str(ctx_server.ctx, tokens.cbegin(), tokens.cend());
  2839. }
  2840. const json data = format_detokenized_response(content);
  2841. return res.set_content(data.dump(), "application/json; charset=utf-8");
  2842. };
  2843. const auto handle_embeddings = [&params, &ctx_server, &res_error](const httplib::Request & req, httplib::Response & res) {
  2844. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2845. if (!params.embedding) {
  2846. res.status = 501;
  2847. res.set_content("This server does not support embeddings. Start it with `--embeddings`", "text/plain; charset=utf-8");
  2848. return;
  2849. }
  2850. const json body = json::parse(req.body);
  2851. bool is_openai = false;
  2852. // an input prompt can be a string or a list of tokens (integer)
  2853. json prompt;
  2854. if (body.count("input") != 0) {
  2855. is_openai = true;
  2856. prompt = body["input"];
  2857. } else if (body.count("content") != 0) {
  2858. // with "content", we only support single prompt
  2859. prompt = std::vector<std::string>{body["content"]};
  2860. } else {
  2861. res_error(res, format_error_response("\"input\" or \"content\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  2862. return;
  2863. }
  2864. // create and queue the task
  2865. json responses;
  2866. {
  2867. const int id_task = ctx_server.queue_tasks.get_new_id();
  2868. ctx_server.queue_results.add_waiting_task_id(id_task);
  2869. ctx_server.request_completion(id_task, -1, {{"prompt", prompt}}, false, true);
  2870. // get the result
  2871. server_task_result result = ctx_server.queue_results.recv(id_task);
  2872. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2873. if (!result.error) {
  2874. if (result.data.count("results")) {
  2875. // result for multi-task
  2876. responses = result.data["results"];
  2877. } else {
  2878. // result for single task
  2879. responses = std::vector<json>{result.data};
  2880. }
  2881. } else {
  2882. // error received, ignore everything else
  2883. res_error(res, result.data);
  2884. return;
  2885. }
  2886. }
  2887. // write JSON response
  2888. json root = is_openai
  2889. ? format_embeddings_response_oaicompat(body, responses)
  2890. : responses[0];
  2891. return res.set_content(root.dump(), "application/json; charset=utf-8");
  2892. };
  2893. auto handle_static_file = [](unsigned char * content, size_t len, const char * mime_type) {
  2894. return [content, len, mime_type](const httplib::Request &, httplib::Response & res) {
  2895. res.set_content(reinterpret_cast<const char*>(content), len, mime_type);
  2896. return false;
  2897. };
  2898. };
  2899. //
  2900. // Router
  2901. //
  2902. // register static assets routes
  2903. if (!sparams.public_path.empty()) {
  2904. // Set the base directory for serving static files
  2905. svr->set_base_dir(sparams.public_path);
  2906. }
  2907. // using embedded static files
  2908. svr->Get("/", handle_static_file(index_html, index_html_len, "text/html; charset=utf-8"));
  2909. svr->Get("/index.js", handle_static_file(index_js, index_js_len, "text/javascript; charset=utf-8"));
  2910. svr->Get("/completion.js", handle_static_file(completion_js, completion_js_len, "text/javascript; charset=utf-8"));
  2911. svr->Get("/json-schema-to-grammar.mjs", handle_static_file(
  2912. json_schema_to_grammar_mjs, json_schema_to_grammar_mjs_len, "text/javascript; charset=utf-8"));
  2913. // register API routes
  2914. svr->Get ("/health", handle_health);
  2915. svr->Get ("/slots", handle_slots);
  2916. svr->Get ("/metrics", handle_metrics);
  2917. svr->Get ("/props", handle_props);
  2918. svr->Get ("/v1/models", handle_models);
  2919. svr->Post("/completion", handle_completions); // legacy
  2920. svr->Post("/completions", handle_completions);
  2921. svr->Post("/v1/completions", handle_completions);
  2922. svr->Post("/chat/completions", handle_chat_completions);
  2923. svr->Post("/v1/chat/completions", handle_chat_completions);
  2924. svr->Post("/infill", handle_infill);
  2925. svr->Post("/embedding", handle_embeddings); // legacy
  2926. svr->Post("/embeddings", handle_embeddings);
  2927. svr->Post("/v1/embeddings", handle_embeddings);
  2928. svr->Post("/tokenize", handle_tokenize);
  2929. svr->Post("/detokenize", handle_detokenize);
  2930. //
  2931. // Start the server
  2932. //
  2933. if (sparams.n_threads_http < 1) {
  2934. // +2 threads for monitoring endpoints
  2935. sparams.n_threads_http = std::max(params.n_parallel + 2, (int32_t) std::thread::hardware_concurrency() - 1);
  2936. }
  2937. log_data["n_threads_http"] = std::to_string(sparams.n_threads_http);
  2938. svr->new_task_queue = [&sparams] { return new httplib::ThreadPool(sparams.n_threads_http); };
  2939. LOG_INFO("HTTP server listening", log_data);
  2940. // run the HTTP server in a thread - see comment below
  2941. std::thread t([&]() {
  2942. if (!svr->listen_after_bind()) {
  2943. state.store(SERVER_STATE_ERROR);
  2944. return 1;
  2945. }
  2946. return 0;
  2947. });
  2948. ctx_server.queue_tasks.on_new_task(std::bind(
  2949. &server_context::process_single_task, &ctx_server, std::placeholders::_1));
  2950. ctx_server.queue_tasks.on_finish_multitask(std::bind(
  2951. &server_context::on_finish_multitask, &ctx_server, std::placeholders::_1));
  2952. ctx_server.queue_tasks.on_update_slots(std::bind(
  2953. &server_context::update_slots, &ctx_server));
  2954. ctx_server.queue_results.on_multitask_update(std::bind(
  2955. &server_queue::update_multitask,
  2956. &ctx_server.queue_tasks,
  2957. std::placeholders::_1,
  2958. std::placeholders::_2,
  2959. std::placeholders::_3
  2960. ));
  2961. shutdown_handler = [&](int) {
  2962. ctx_server.queue_tasks.terminate();
  2963. };
  2964. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  2965. struct sigaction sigint_action;
  2966. sigint_action.sa_handler = signal_handler;
  2967. sigemptyset (&sigint_action.sa_mask);
  2968. sigint_action.sa_flags = 0;
  2969. sigaction(SIGINT, &sigint_action, NULL);
  2970. #elif defined (_WIN32)
  2971. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  2972. return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
  2973. };
  2974. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  2975. #endif
  2976. ctx_server.queue_tasks.start_loop();
  2977. svr->stop();
  2978. t.join();
  2979. llama_backend_free();
  2980. return 0;
  2981. }