server.cpp 152 KB

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