server.cpp 143 KB

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