server.cpp 154 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835
  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.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. size_t safe_offset = std::min(slot.generated_token_probs.size(), stop_word_toks.size());
  1142. probs = std::vector<completion_token_output>(
  1143. slot.generated_token_probs.begin(),
  1144. slot.generated_token_probs.end() - safe_offset);
  1145. } else {
  1146. probs = std::vector<completion_token_output>(
  1147. slot.generated_token_probs.begin(),
  1148. slot.generated_token_probs.end());
  1149. }
  1150. res.data["completion_probabilities"] = probs_vector_to_json(ctx, probs);
  1151. }
  1152. if (slot.oaicompat) {
  1153. res.data["oaicompat_token_ctr"] = slot.n_decoded;
  1154. res.data["model"] = slot.oaicompat_model;
  1155. }
  1156. queue_results.send(res);
  1157. }
  1158. void send_embedding(const server_slot & slot, const llama_batch & batch) {
  1159. server_task_result res;
  1160. res.id = slot.id_task;
  1161. res.id_multi = slot.id_multi;
  1162. res.error = false;
  1163. res.stop = true;
  1164. const int n_embd = llama_n_embd(model);
  1165. std::vector<float> embd_res(n_embd, 0.0f);
  1166. for (int i = 0; i < batch.n_tokens; ++i) {
  1167. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id + 1) {
  1168. continue;
  1169. }
  1170. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1171. if (embd == NULL) {
  1172. embd = llama_get_embeddings_ith(ctx, i);
  1173. }
  1174. if (embd == NULL) {
  1175. LOG_ERROR("failed to get embeddings", {
  1176. {"token", batch.token [i]},
  1177. {"seq_id", batch.seq_id[i][0]}
  1178. });
  1179. res.data = json {
  1180. {"embedding", std::vector<float>(n_embd, 0.0f)},
  1181. };
  1182. continue;
  1183. }
  1184. llama_embd_normalize(embd, embd_res.data(), n_embd);
  1185. res.data = json {
  1186. {"embedding", embd_res},
  1187. };
  1188. }
  1189. queue_results.send(res);
  1190. }
  1191. void request_completion(int id_task, int id_multi, json data, bool infill, bool embedding) {
  1192. server_task task;
  1193. task.id = id_task;
  1194. task.id_multi = id_multi;
  1195. task.id_target = 0;
  1196. task.data = std::move(data);
  1197. task.infill = infill;
  1198. task.embedding = embedding;
  1199. task.type = SERVER_TASK_TYPE_COMPLETION;
  1200. // when a completion task's prompt array is not a singleton, we split it into multiple requests
  1201. // otherwise, it's a single-prompt task, we actually queue it
  1202. // if there's numbers in the prompt array it will be treated as an array of tokens
  1203. if (task.data.count("prompt") != 0 && task.data.at("prompt").size() > 1) {
  1204. bool numbers = false;
  1205. for (const auto & e : task.data.at("prompt")) {
  1206. if (e.is_number()) {
  1207. numbers = true;
  1208. break;
  1209. }
  1210. }
  1211. // NOTE: split_multiprompt_task() does not handle a mix of strings and numbers,
  1212. // it will completely stall the server. I don't know where the bug for this is.
  1213. //
  1214. // if there are numbers, it needs to be treated like a single prompt,
  1215. // queue_tasks handles a mix of strings and numbers just fine.
  1216. if (numbers) {
  1217. queue_tasks.post(task);
  1218. } else {
  1219. split_multiprompt_task(id_task, task);
  1220. }
  1221. } else {
  1222. queue_tasks.post(task);
  1223. }
  1224. }
  1225. void request_cancel(int id_task) {
  1226. server_task task;
  1227. task.type = SERVER_TASK_TYPE_CANCEL;
  1228. task.id_target = id_task;
  1229. queue_tasks.post(task);
  1230. }
  1231. void split_multiprompt_task(int id_multi, const server_task & multiprompt_task) {
  1232. const int prompt_count = multiprompt_task.data.at("prompt").size();
  1233. if (prompt_count <= 1) {
  1234. send_error(multiprompt_task, "error while handling multiple prompts");
  1235. return;
  1236. }
  1237. // generate all the ID for subtask
  1238. std::vector<int> subtask_ids(prompt_count);
  1239. for (int i = 0; i < prompt_count; i++) {
  1240. subtask_ids[i] = queue_tasks.get_new_id();
  1241. }
  1242. // queue up the multitask so we can track its subtask progression
  1243. queue_tasks.add_multitask(id_multi, subtask_ids);
  1244. // add subtasks
  1245. for (int i = 0; i < prompt_count; i++) {
  1246. json subtask_data = multiprompt_task.data;
  1247. subtask_data["prompt"] = subtask_data["prompt"][i];
  1248. // subtasks inherit everything else (infill mode, embedding mode, etc.)
  1249. request_completion(subtask_ids[i], id_multi, subtask_data, multiprompt_task.infill, multiprompt_task.embedding);
  1250. }
  1251. }
  1252. void process_single_task(const server_task & task) {
  1253. switch (task.type) {
  1254. case SERVER_TASK_TYPE_COMPLETION:
  1255. {
  1256. server_slot * slot = get_slot(json_value(task.data, "id_slot", -1));
  1257. if (slot == nullptr) {
  1258. // if no slot is available, we defer this task for processing later
  1259. LOG_VERBOSE("no slot is available", {{"id_task", task.id}});
  1260. queue_tasks.defer(task);
  1261. break;
  1262. }
  1263. if (task.data.contains("system_prompt")) {
  1264. system_prompt_set(task.data["system_prompt"]);
  1265. for (server_slot & slot : slots) {
  1266. slot.n_past = 0;
  1267. slot.n_past_se = 0;
  1268. }
  1269. }
  1270. slot->reset();
  1271. slot->id_task = task.id;
  1272. slot->id_multi = task.id_multi;
  1273. slot->infill = task.infill;
  1274. slot->embedding = task.embedding;
  1275. if (!launch_slot_with_task(*slot, task)) {
  1276. LOG_ERROR("error while launching slot", task.data);
  1277. break;
  1278. }
  1279. } break;
  1280. case SERVER_TASK_TYPE_CANCEL:
  1281. {
  1282. // release slot linked with the task id
  1283. for (auto & slot : slots) {
  1284. if (slot.id_task == task.id_target) {
  1285. slot.release();
  1286. break;
  1287. }
  1288. }
  1289. } break;
  1290. case SERVER_TASK_TYPE_NEXT_RESPONSE:
  1291. {
  1292. // do nothing
  1293. } break;
  1294. case SERVER_TASK_TYPE_METRICS:
  1295. {
  1296. json slots_data = json::array();
  1297. int n_idle_slots = 0;
  1298. int n_processing_slots = 0;
  1299. for (server_slot & slot : slots) {
  1300. json slot_data = get_formated_generation(slot);
  1301. slot_data["id"] = slot.id;
  1302. slot_data["id_task"] = slot.id_task;
  1303. slot_data["state"] = slot.state;
  1304. slot_data["prompt"] = slot.prompt;
  1305. slot_data["next_token"] = {
  1306. {"has_next_token", slot.has_next_token},
  1307. {"n_remain", slot.n_remaining},
  1308. {"n_decoded", slot.n_decoded},
  1309. {"stopped_eos", slot.stopped_eos},
  1310. {"stopped_word", slot.stopped_word},
  1311. {"stopped_limit", slot.stopped_limit},
  1312. {"stopping_word", slot.stopping_word},
  1313. };
  1314. if (slot_data["state"] == SLOT_STATE_IDLE) {
  1315. n_idle_slots++;
  1316. } else {
  1317. n_processing_slots++;
  1318. }
  1319. slots_data.push_back(slot_data);
  1320. }
  1321. LOG_INFO("slot data", {
  1322. {"id_task", task.id},
  1323. {"n_idle_slots", n_idle_slots},
  1324. {"n_processing_slots", n_processing_slots}
  1325. });
  1326. LOG_VERBOSE("slot data", {
  1327. {"id_task", task.id},
  1328. {"n_idle_slots", n_idle_slots},
  1329. {"n_processing_slots", n_processing_slots},
  1330. {"slots", slots_data}
  1331. });
  1332. server_task_result res;
  1333. res.id = task.id;
  1334. res.id_multi = task.id_multi;
  1335. res.stop = true;
  1336. res.error = false;
  1337. res.data = {
  1338. { "idle", n_idle_slots },
  1339. { "processing", n_processing_slots },
  1340. { "deferred", queue_tasks.queue_tasks_deferred.size() },
  1341. { "t_start", metrics.t_start},
  1342. { "n_prompt_tokens_processed_total", metrics.n_prompt_tokens_processed_total},
  1343. { "t_tokens_generation_total", metrics.t_tokens_generation_total},
  1344. { "n_tokens_predicted_total", metrics.n_tokens_predicted_total},
  1345. { "t_prompt_processing_total", metrics.t_prompt_processing_total},
  1346. { "n_prompt_tokens_processed", metrics.n_prompt_tokens_processed},
  1347. { "t_prompt_processing", metrics.t_prompt_processing},
  1348. { "n_tokens_predicted", metrics.n_tokens_predicted},
  1349. { "t_tokens_generation", metrics.t_tokens_generation},
  1350. { "kv_cache_tokens_count", llama_get_kv_cache_token_count(ctx)},
  1351. { "kv_cache_used_cells", llama_get_kv_cache_used_cells(ctx)},
  1352. { "slots", slots_data },
  1353. };
  1354. if (json_value(task.data, "reset_bucket", false)) {
  1355. metrics.reset_bucket();
  1356. }
  1357. queue_results.send(res);
  1358. } break;
  1359. case SERVER_TASK_TYPE_SLOT_SAVE:
  1360. {
  1361. int id_slot = task.data["id_slot"];
  1362. server_slot * slot = get_slot(id_slot);
  1363. if (slot == nullptr) {
  1364. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1365. break;
  1366. }
  1367. const size_t token_count = slot->cache_tokens.size();
  1368. const int64_t t_start = ggml_time_us();
  1369. std::string filename = task.data["filename"];
  1370. std::string filepath = task.data["filepath"];
  1371. const size_t nwrite = llama_state_seq_save_file(ctx, filepath.c_str(), slot->id + 1, slot->cache_tokens.data(), token_count);
  1372. const int64_t t_end = ggml_time_us();
  1373. const double t_save_ms = (t_end - t_start) / 1000.0;
  1374. server_task_result result;
  1375. result.id = task.id;
  1376. result.stop = true;
  1377. result.error = false;
  1378. result.data = json {
  1379. { "id_slot", id_slot },
  1380. { "filename", filename },
  1381. { "n_saved", token_count }, // tokens saved
  1382. { "n_written", nwrite }, // bytes written
  1383. { "timings", {
  1384. { "save_ms", t_save_ms }
  1385. } }
  1386. };
  1387. queue_results.send(result);
  1388. } break;
  1389. case SERVER_TASK_TYPE_SLOT_RESTORE:
  1390. {
  1391. int id_slot = task.data["id_slot"];
  1392. server_slot * slot = get_slot(id_slot);
  1393. if (slot == nullptr) {
  1394. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1395. break;
  1396. }
  1397. const int64_t t_start = ggml_time_us();
  1398. std::string filename = task.data["filename"];
  1399. std::string filepath = task.data["filepath"];
  1400. slot->cache_tokens.resize(slot->n_ctx);
  1401. size_t token_count = 0;
  1402. 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);
  1403. if (nread == 0) {
  1404. slot->cache_tokens.resize(0);
  1405. send_error(task, "Unable to restore slot, no available space in KV cache or invalid slot save file", ERROR_TYPE_INVALID_REQUEST);
  1406. break;
  1407. }
  1408. slot->cache_tokens.resize(token_count);
  1409. const int64_t t_end = ggml_time_us();
  1410. const double t_restore_ms = (t_end - t_start) / 1000.0;
  1411. server_task_result result;
  1412. result.id = task.id;
  1413. result.stop = true;
  1414. result.error = false;
  1415. result.data = json {
  1416. { "id_slot", id_slot },
  1417. { "filename", filename },
  1418. { "n_restored", token_count }, // tokens restored
  1419. { "n_read", nread }, // bytes read
  1420. { "timings", {
  1421. { "restore_ms", t_restore_ms }
  1422. } }
  1423. };
  1424. queue_results.send(result);
  1425. } break;
  1426. case SERVER_TASK_TYPE_SLOT_ERASE:
  1427. {
  1428. int id_slot = task.data["id_slot"];
  1429. server_slot * slot = get_slot(id_slot);
  1430. if (slot == nullptr) {
  1431. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1432. break;
  1433. }
  1434. // Erase token cache
  1435. const size_t n_erased = slot->cache_tokens.size();
  1436. llama_kv_cache_seq_rm(ctx, slot->id + 1, -1, -1);
  1437. slot->cache_tokens.clear();
  1438. server_task_result result;
  1439. result.id = task.id;
  1440. result.stop = true;
  1441. result.error = false;
  1442. result.data = json {
  1443. { "id_slot", id_slot },
  1444. { "n_erased", n_erased }
  1445. };
  1446. queue_results.send(result);
  1447. } break;
  1448. }
  1449. }
  1450. void on_finish_multitask(const server_task_multi & multitask) {
  1451. // all subtasks done == multitask is done
  1452. server_task_result result;
  1453. result.id = multitask.id;
  1454. result.stop = true;
  1455. result.error = false;
  1456. // collect json results into one json result
  1457. std::vector<json> result_jsons;
  1458. for (const auto & subres : multitask.results) {
  1459. result_jsons.push_back(subres.data);
  1460. result.error = result.error && subres.error;
  1461. }
  1462. result.data = json {
  1463. { "results", result_jsons }
  1464. };
  1465. queue_results.send(result);
  1466. }
  1467. void update_slots() {
  1468. if (system_need_update) {
  1469. system_prompt_update();
  1470. }
  1471. // release slots
  1472. for (auto & slot : slots) {
  1473. if (slot.command == SLOT_COMMAND_RELEASE) {
  1474. slot.state = SLOT_STATE_IDLE;
  1475. slot.command = SLOT_COMMAND_NONE;
  1476. slot.t_last_used = ggml_time_us();
  1477. LOG_INFO("slot released", {
  1478. {"id_slot", slot.id},
  1479. {"id_task", slot.id_task},
  1480. {"n_ctx", n_ctx},
  1481. {"n_past", slot.n_past},
  1482. {"n_system_tokens", system_tokens.size()},
  1483. {"n_cache_tokens", slot.cache_tokens.size()},
  1484. {"truncated", slot.truncated}
  1485. });
  1486. queue_tasks.notify_slot_changed();
  1487. }
  1488. }
  1489. // check if all slots are idle
  1490. {
  1491. bool all_idle = true;
  1492. for (auto & slot : slots) {
  1493. if (slot.state != SLOT_STATE_IDLE || slot.command != SLOT_COMMAND_NONE) {
  1494. all_idle = false;
  1495. break;
  1496. }
  1497. }
  1498. if (all_idle) {
  1499. LOG_INFO("all slots are idle", {});
  1500. if (system_prompt.empty() && clean_kv_cache) {
  1501. kv_cache_clear();
  1502. }
  1503. return;
  1504. }
  1505. }
  1506. {
  1507. LOG_VERBOSE("posting NEXT_RESPONSE", {});
  1508. server_task task;
  1509. task.type = SERVER_TASK_TYPE_NEXT_RESPONSE;
  1510. task.id_target = -1;
  1511. queue_tasks.post(task);
  1512. }
  1513. // apply context-shift if needed
  1514. // TODO: simplify and improve
  1515. for (server_slot & slot : slots) {
  1516. if (slot.ga_n == 1) {
  1517. if (slot.is_processing() && (int) system_tokens.size() + slot.n_past >= slot.n_ctx - 1) {
  1518. // Shift context
  1519. const int n_keep = slot.params.n_keep + add_bos_token;
  1520. const int n_left = (int) system_tokens.size() + slot.n_past - n_keep;
  1521. const int n_discard = slot.params.n_discard ? slot.params.n_discard : (n_left / 2);
  1522. LOG_INFO("slot context shift", {
  1523. {"id_slot", slot.id},
  1524. {"id_task", slot.id_task},
  1525. {"n_keep", n_keep},
  1526. {"n_left", n_left},
  1527. {"n_discard", n_discard},
  1528. {"n_ctx", n_ctx},
  1529. {"n_past", slot.n_past},
  1530. {"n_system_tokens", system_tokens.size()},
  1531. {"n_cache_tokens", slot.cache_tokens.size()}
  1532. });
  1533. llama_kv_cache_seq_rm (ctx, slot.id + 1, n_keep , n_keep + n_discard);
  1534. llama_kv_cache_seq_add(ctx, slot.id + 1, n_keep + n_discard, system_tokens.size() + slot.n_past, -n_discard);
  1535. if (slot.params.cache_prompt) {
  1536. for (size_t i = n_keep + n_discard; i < slot.cache_tokens.size(); i++) {
  1537. slot.cache_tokens[i - n_discard] = slot.cache_tokens[i];
  1538. }
  1539. slot.cache_tokens.resize(slot.cache_tokens.size() - n_discard);
  1540. }
  1541. slot.n_past -= n_discard;
  1542. slot.truncated = true;
  1543. }
  1544. }
  1545. }
  1546. // start populating the batch for this iteration
  1547. llama_batch_clear(batch);
  1548. // frist, add sampled tokens from any ongoing sequences
  1549. for (auto & slot : slots) {
  1550. if (slot.state == SLOT_STATE_IDLE) {
  1551. continue;
  1552. }
  1553. slot.i_batch = batch.n_tokens;
  1554. const int32_t slot_npast = slot.n_past_se > 0 ? slot.n_past_se : slot.n_past;
  1555. // TODO: we always have to take into account the "system_tokens"
  1556. // this is not great and needs to be improved somehow
  1557. llama_batch_add(batch, slot.sampled, system_tokens.size() + slot_npast, { slot.id + 1 }, true);
  1558. slot.n_past += 1;
  1559. if (slot.params.cache_prompt) {
  1560. slot.cache_tokens.push_back(slot.sampled);
  1561. }
  1562. LOG_VERBOSE("slot decode token", {
  1563. {"id_slot", slot.id},
  1564. {"id_task", slot.id_task},
  1565. {"n_ctx", n_ctx},
  1566. {"n_past", slot.n_past},
  1567. {"n_system_tokens", system_tokens.size()},
  1568. {"n_cache_tokens", slot.cache_tokens.size()},
  1569. {"truncated", slot.truncated}
  1570. });
  1571. }
  1572. // process in chunks of params.n_batch
  1573. int32_t n_batch = llama_n_batch(ctx);
  1574. int32_t n_ubatch = llama_n_ubatch(ctx);
  1575. // next, batch any pending prompts without exceeding n_batch
  1576. if (params.cont_batching || batch.n_tokens == 0) {
  1577. for (auto & slot : slots) {
  1578. // this slot still has a prompt to be processed
  1579. if (slot.state == SLOT_STATE_IDLE && slot.command == SLOT_COMMAND_LOAD_PROMPT) {
  1580. auto & prompt_tokens = slot.prompt_tokens;
  1581. // we haven't tokenized the prompt yet - do it now:
  1582. if (prompt_tokens.empty()) {
  1583. LOG_VERBOSE("tokenizing prompt", {
  1584. {"id_slot", slot.id},
  1585. {"id_task", slot.id_task}
  1586. });
  1587. slot.t_start_process_prompt = ggml_time_us();
  1588. slot.t_start_generation = 0;
  1589. if (slot.infill) {
  1590. bool suff_rm_leading_spc = true;
  1591. if (params.input_suffix.find_first_of(' ') == 0 && params.input_suffix.size() > 1) {
  1592. params.input_suffix.erase(0, 1);
  1593. suff_rm_leading_spc = false;
  1594. }
  1595. auto prefix_tokens = tokenize(slot.params.input_prefix, false);
  1596. auto suffix_tokens = tokenize(slot.params.input_suffix, false);
  1597. const int space_token = 29871; // TODO: this should not be hardcoded
  1598. if (suff_rm_leading_spc && !suffix_tokens.empty() && suffix_tokens[0] == space_token) {
  1599. suffix_tokens.erase(suffix_tokens.begin());
  1600. }
  1601. prefix_tokens.insert(prefix_tokens.begin(), llama_token_prefix(model));
  1602. prefix_tokens.insert(prefix_tokens.begin(), llama_token_bos(model)); // always add BOS
  1603. prefix_tokens.insert(prefix_tokens.end(), llama_token_suffix(model));
  1604. prefix_tokens.insert(prefix_tokens.end(), suffix_tokens.begin(), suffix_tokens.end());
  1605. prefix_tokens.push_back(llama_token_middle(model));
  1606. prompt_tokens = prefix_tokens;
  1607. } else {
  1608. prompt_tokens = tokenize(slot.prompt, system_prompt.empty()); // add BOS if there isn't system prompt
  1609. }
  1610. slot.n_past = 0;
  1611. slot.n_prompt_tokens = prompt_tokens.size();
  1612. LOG_VERBOSE("prompt tokenized", {
  1613. {"id_slot", slot.id},
  1614. {"id_task", slot.id_task},
  1615. {"n_ctx", slot.n_ctx},
  1616. {"n_keep", slot.params.n_keep},
  1617. {"n_prompt_tokens", slot.n_prompt_tokens},
  1618. {"prompt_tokens", tokens_to_str(ctx, prompt_tokens.cbegin(), prompt_tokens.cend())},
  1619. });
  1620. // empty prompt passed -> release the slot and send empty response
  1621. if (prompt_tokens.empty()) {
  1622. LOG_INFO("empty prompt - releasing slot", {
  1623. {"id_slot", slot.id},
  1624. {"id_task", slot.id_task}
  1625. });
  1626. slot.state = SLOT_STATE_PROCESSING;
  1627. slot.command = SLOT_COMMAND_NONE;
  1628. slot.release();
  1629. slot.print_timings();
  1630. send_final_response(slot);
  1631. continue;
  1632. }
  1633. if (slot.embedding) {
  1634. // this prompt is too large to process - discard it
  1635. if (slot.n_prompt_tokens > n_ubatch) {
  1636. slot.state = SLOT_STATE_PROCESSING;
  1637. slot.command = SLOT_COMMAND_NONE;
  1638. slot.release();
  1639. slot.print_timings();
  1640. send_final_response(slot);
  1641. continue;
  1642. }
  1643. } else {
  1644. if (slot.params.n_keep < 0) {
  1645. slot.params.n_keep = slot.n_prompt_tokens;
  1646. }
  1647. slot.params.n_keep = std::min(slot.n_ctx - 4, slot.params.n_keep);
  1648. // if input prompt is too big, truncate it (if group attention self-extend is disabled)
  1649. if (slot.ga_n == 1 && slot.n_prompt_tokens >= slot.n_ctx) {
  1650. const int n_left = slot.n_ctx - slot.params.n_keep;
  1651. const int n_block_size = n_left / 2;
  1652. const int erased_blocks = (slot.n_prompt_tokens - slot.params.n_keep - n_block_size) / n_block_size;
  1653. std::vector<llama_token> new_tokens(
  1654. prompt_tokens.begin(),
  1655. prompt_tokens.begin() + slot.params.n_keep);
  1656. new_tokens.insert(
  1657. new_tokens.end(),
  1658. prompt_tokens.begin() + slot.params.n_keep + erased_blocks * n_block_size,
  1659. prompt_tokens.end());
  1660. prompt_tokens = std::move(new_tokens);
  1661. slot.truncated = true;
  1662. slot.n_prompt_tokens = prompt_tokens.size();
  1663. LOG_VERBOSE("input truncated", {
  1664. {"id_slot", slot.id},
  1665. {"id_task", slot.id_task},
  1666. {"n_ctx", slot.n_ctx},
  1667. {"n_keep", slot.params.n_keep},
  1668. {"n_left", n_left},
  1669. {"n_prompt_tokens", slot.n_prompt_tokens},
  1670. {"prompt_tokens", tokens_to_str(ctx, prompt_tokens.cbegin(), prompt_tokens.cend())},
  1671. });
  1672. GGML_ASSERT(slot.n_prompt_tokens < slot.n_ctx);
  1673. }
  1674. llama_sampling_reset(slot.ctx_sampling);
  1675. if (!slot.params.cache_prompt) {
  1676. slot.n_past_se = 0;
  1677. slot.ga_i = 0;
  1678. } else {
  1679. GGML_ASSERT(slot.ga_n == 1);
  1680. // reuse any previously computed tokens that are common with the new prompt
  1681. slot.n_past = common_part(slot.cache_tokens, prompt_tokens);
  1682. // push the prompt into the sampling context (do not apply grammar)
  1683. for (int i = 0; i < slot.n_past; ++i) {
  1684. llama_sampling_accept(slot.ctx_sampling, ctx, slot.cache_tokens[i], false);
  1685. }
  1686. }
  1687. }
  1688. if (slot.n_past == slot.n_prompt_tokens && slot.n_past > 0) {
  1689. // we have to evaluate at least 1 token to generate logits.
  1690. LOG_INFO("we have to evaluate at least 1 token to generate logits", {
  1691. { "id_slot", slot.id },
  1692. { "id_task", slot.id_task }
  1693. });
  1694. slot.n_past--;
  1695. if (slot.ga_i > 0) {
  1696. slot.n_past_se--;
  1697. }
  1698. }
  1699. slot.n_prompt_tokens_processed = 0;
  1700. }
  1701. if (slot.embedding) {
  1702. // cannot fit the prompt in the current batch - will try next iter
  1703. if (batch.n_tokens + slot.n_prompt_tokens > n_batch) {
  1704. continue;
  1705. }
  1706. }
  1707. // keep only the common part
  1708. int p0 = (int) system_tokens.size() + slot.n_past;
  1709. if (!llama_kv_cache_seq_rm(ctx, slot.id + 1, p0, -1)) {
  1710. // could not partially delete (likely using a non-Transformer model)
  1711. llama_kv_cache_seq_rm(ctx, slot.id + 1, -1, -1);
  1712. p0 = (int) system_tokens.size();
  1713. if (p0 != 0) {
  1714. // copy over the system prompt when there is one
  1715. llama_kv_cache_seq_cp(ctx, 0, slot.id + 1, -1, -1);
  1716. }
  1717. // there is no common part left (except for the system prompt)
  1718. slot.n_past = 0;
  1719. slot.n_past_se = 0;
  1720. slot.ga_i = 0;
  1721. // TODO: is the system prompt ever in the sampling context?
  1722. llama_sampling_reset(slot.ctx_sampling);
  1723. }
  1724. // remove the non-common part from the cache
  1725. slot.cache_tokens.resize(slot.n_past);
  1726. LOG_INFO("kv cache rm [p0, end)", {
  1727. { "id_slot", slot.id },
  1728. { "id_task", slot.id_task },
  1729. { "p0", p0 }
  1730. });
  1731. int32_t slot_npast = slot.n_past_se > 0 ? slot.n_past_se : slot.n_past;
  1732. int32_t ga_i = slot.ga_i;
  1733. int32_t ga_n = slot.ga_n;
  1734. int32_t ga_w = slot.ga_w;
  1735. // add prompt tokens for processing in the current batch
  1736. // TODO: the self-extend stuff here is a mess - simplify and/or abstract it somehow
  1737. for (; slot.n_past < slot.n_prompt_tokens && batch.n_tokens < n_batch; ++slot.n_past) {
  1738. if (slot.ga_n != 1) {
  1739. while (slot_npast >= ga_i + ga_w) {
  1740. const int bd = (ga_w/ga_n)*(ga_n - 1);
  1741. slot_npast -= bd;
  1742. ga_i += ga_w/ga_n;
  1743. }
  1744. }
  1745. llama_batch_add(batch, prompt_tokens[slot.n_past], system_tokens.size() + slot_npast, { slot.id + 1 }, false);
  1746. if (slot.params.cache_prompt) {
  1747. slot.cache_tokens.push_back(prompt_tokens[slot.n_past]);
  1748. }
  1749. slot.n_prompt_tokens_processed++;
  1750. slot_npast++;
  1751. }
  1752. LOG_VERBOSE("prompt processing progress", {
  1753. {"id_slot", slot.id},
  1754. {"n_past", slot.n_past},
  1755. {"n_ctx", n_ctx},
  1756. {"n_tokens", batch.n_tokens},
  1757. {"progress", (float) slot.n_prompt_tokens_processed / slot.n_prompt_tokens},
  1758. });
  1759. // entire prompt has been processed - start decoding new tokens
  1760. if (slot.n_past == slot.n_prompt_tokens) {
  1761. slot.state = SLOT_STATE_PROCESSING;
  1762. slot.command = SLOT_COMMAND_NONE;
  1763. GGML_ASSERT(batch.n_tokens > 0);
  1764. // extract the logits only for the last token
  1765. batch.logits[batch.n_tokens - 1] = true;
  1766. slot.n_decoded = 0;
  1767. slot.i_batch = batch.n_tokens - 1;
  1768. LOG_VERBOSE("prompt done", {
  1769. {"id_slot", slot.id},
  1770. {"n_past", slot.n_past},
  1771. {"n_ctx", n_ctx},
  1772. {"n_tokens", batch.n_tokens},
  1773. });
  1774. }
  1775. }
  1776. if (batch.n_tokens >= n_batch) {
  1777. break;
  1778. }
  1779. }
  1780. }
  1781. if (batch.n_tokens == 0) {
  1782. LOG_VERBOSE("no tokens to decode", {});
  1783. return;
  1784. }
  1785. LOG_VERBOSE("decoding batch", {
  1786. {"n_tokens", batch.n_tokens},
  1787. });
  1788. // process the created batch of tokens
  1789. for (int32_t i = 0; i < batch.n_tokens; i += n_batch) {
  1790. const int32_t n_tokens = std::min(n_batch, batch.n_tokens - i);
  1791. for (auto & slot : slots) {
  1792. if (slot.ga_n != 1) {
  1793. // context extension via Self-Extend
  1794. // TODO: simplify and/or abstract this
  1795. while (slot.n_past_se >= slot.ga_i + slot.ga_w) {
  1796. const int ib = (slot.ga_n * slot.ga_i) / slot.ga_w;
  1797. const int bd = (slot.ga_w / slot.ga_n) * (slot.ga_n - 1);
  1798. const int dd = (slot.ga_w / slot.ga_n) - ib * bd - slot.ga_w;
  1799. LOG_TEE("\n");
  1800. 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);
  1801. 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);
  1802. 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);
  1803. llama_kv_cache_seq_add(ctx, slot.id + 1, slot.ga_i, slot.n_past_se, ib * bd);
  1804. 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);
  1805. llama_kv_cache_seq_add(ctx, slot.id + 1, slot.ga_i + ib * bd + slot.ga_w, slot.n_past_se + ib * bd, dd);
  1806. slot.n_past_se -= bd;
  1807. slot.ga_i += slot.ga_w / slot.ga_n;
  1808. 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);
  1809. }
  1810. slot.n_past_se += n_tokens;
  1811. }
  1812. }
  1813. llama_batch batch_view = {
  1814. n_tokens,
  1815. batch.token + i,
  1816. nullptr,
  1817. batch.pos + i,
  1818. batch.n_seq_id + i,
  1819. batch.seq_id + i,
  1820. batch.logits + i,
  1821. 0, 0, 0, // unused
  1822. };
  1823. const int ret = llama_decode(ctx, batch_view);
  1824. if (ret != 0) {
  1825. if (n_batch == 1 || ret < 0) {
  1826. // if you get here, it means the KV cache is full - try increasing it via the context size
  1827. LOG_ERROR("failed to decode the batch: KV cache is full - try increasing it via the context size", {
  1828. {"i", i},
  1829. {"n_batch", ret},
  1830. {"ret", ret},
  1831. });
  1832. for (auto & slot : slots) {
  1833. slot.state = SLOT_STATE_PROCESSING;
  1834. slot.command = SLOT_COMMAND_NONE;
  1835. slot.release();
  1836. send_error(slot, "Input prompt is too big compared to KV size. Please try increasing KV size.");
  1837. }
  1838. break; // break loop of n_batch
  1839. }
  1840. // retry with half the batch size to try to find a free slot in the KV cache
  1841. n_batch /= 2;
  1842. i -= n_batch;
  1843. 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", {
  1844. {"i", i},
  1845. {"n_batch", n_batch},
  1846. {"ret", ret},
  1847. });
  1848. continue; // continue loop of n_batch
  1849. }
  1850. for (auto & slot : slots) {
  1851. if (slot.state != SLOT_STATE_PROCESSING || slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens)) {
  1852. continue; // continue loop of slots
  1853. }
  1854. // prompt evaluated for embedding
  1855. if (slot.embedding) {
  1856. send_embedding(slot, batch_view);
  1857. slot.release();
  1858. slot.i_batch = -1;
  1859. continue; // continue loop of slots
  1860. }
  1861. completion_token_output result;
  1862. const llama_token id = llama_sampling_sample(slot.ctx_sampling, ctx, NULL, slot.i_batch - i);
  1863. llama_sampling_accept(slot.ctx_sampling, ctx, id, true);
  1864. slot.n_decoded += 1;
  1865. if (slot.n_decoded == 1) {
  1866. slot.t_start_generation = ggml_time_us();
  1867. slot.t_prompt_processing = (slot.t_start_generation - slot.t_start_process_prompt) / 1e3;
  1868. metrics.on_prompt_eval(slot);
  1869. }
  1870. llama_token_data_array cur_p = { slot.ctx_sampling->cur.data(), slot.ctx_sampling->cur.size(), false };
  1871. result.tok = id;
  1872. const size_t n_probs = std::min(cur_p.size, (size_t) slot.sparams.n_probs);
  1873. if (n_probs > 0) {
  1874. const size_t n_considered = slot.ctx_sampling->n_considered;
  1875. // Make sure at least n_probs top tokens are at the front of the vector:
  1876. if (slot.sparams.temp == 0.0f && n_probs > n_considered) {
  1877. llama_sample_top_k(ctx, &cur_p, n_probs, 0);
  1878. }
  1879. if (slot.sparams.temp == 0.0f) {
  1880. // With greedy sampling the probabilities have possibly not been calculated.
  1881. for (size_t i = 0; i < n_probs; ++i) {
  1882. result.probs.push_back({
  1883. cur_p.data[i].id,
  1884. i == 0 ? 1.0f : 0.0f
  1885. });
  1886. }
  1887. } else {
  1888. for (size_t i = 0; i < n_probs; ++i) {
  1889. result.probs.push_back({
  1890. cur_p.data[i].id,
  1891. i >= n_considered ? 0.0f : cur_p.data[i].p // Tokens filtered out due to e.g. top_k have 0 probability.
  1892. });
  1893. }
  1894. }
  1895. }
  1896. if (!process_token(result, slot)) {
  1897. slot.release();
  1898. slot.print_timings();
  1899. send_final_response(slot);
  1900. metrics.on_prediction(slot);
  1901. }
  1902. slot.i_batch = -1;
  1903. }
  1904. }
  1905. LOG_VERBOSE("run slots completed", {});
  1906. }
  1907. json model_meta() const {
  1908. return json {
  1909. {"vocab_type", llama_vocab_type (model)},
  1910. {"n_vocab", llama_n_vocab (model)},
  1911. {"n_ctx_train", llama_n_ctx_train (model)},
  1912. {"n_embd", llama_n_embd (model)},
  1913. {"n_params", llama_model_n_params(model)},
  1914. {"size", llama_model_size (model)},
  1915. };
  1916. }
  1917. };
  1918. static void server_print_usage(const char * argv0, const gpt_params & params, const server_params & sparams) {
  1919. printf("usage: %s [options]\n", argv0);
  1920. printf("\n");
  1921. printf("options:\n");
  1922. printf(" -h, --help show this help message and exit\n");
  1923. printf(" -v, --verbose verbose output (default: %s)\n", server_verbose ? "enabled" : "disabled");
  1924. printf(" -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  1925. printf(" -tb N, --threads-batch N number of threads to use during batch and prompt processing (default: same as --threads)\n");
  1926. printf(" --threads-http N number of threads in the http server pool to process requests (default: max(hardware concurrency - 1, --parallel N + 2))\n");
  1927. printf(" -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  1928. printf(" --rope-scaling {none,linear,yarn}\n");
  1929. printf(" RoPE frequency scaling method, defaults to linear unless specified by the model\n");
  1930. printf(" --rope-freq-base N RoPE base frequency (default: loaded from model)\n");
  1931. printf(" --rope-freq-scale N RoPE frequency scaling factor, expands context by a factor of 1/N\n");
  1932. printf(" --yarn-ext-factor N YaRN: extrapolation mix factor (default: 1.0, 0.0 = full interpolation)\n");
  1933. printf(" --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)\n");
  1934. printf(" --yarn-beta-slow N YaRN: high correction dim or alpha (default: %.1f)\n", params.yarn_beta_slow);
  1935. printf(" --yarn-beta-fast N YaRN: low correction dim or beta (default: %.1f)\n", params.yarn_beta_fast);
  1936. printf(" --pooling {none,mean,cls} pooling type for embeddings, use model default if unspecified\n");
  1937. printf(" -dt N, --defrag-thold N\n");
  1938. printf(" KV cache defragmentation threshold (default: %.1f, < 0 - disabled)\n", params.defrag_thold);
  1939. printf(" -b N, --batch-size N logical maximum batch size (default: %d)\n", params.n_batch);
  1940. printf(" -ub N, --ubatch-size N physical maximum batch size (default: %d)\n", params.n_ubatch);
  1941. if (llama_supports_mlock()) {
  1942. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  1943. }
  1944. if (llama_supports_mmap()) {
  1945. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  1946. }
  1947. printf(" --numa TYPE attempt optimizations that help on some NUMA systems\n");
  1948. printf(" - distribute: spread execution evenly over all nodes\n");
  1949. printf(" - isolate: only spawn threads on CPUs on the node that execution started on\n");
  1950. printf(" - numactl: use the CPU map provided my numactl\n");
  1951. if (llama_supports_gpu_offload()) {
  1952. printf(" -ngl N, --n-gpu-layers N\n");
  1953. printf(" number of layers to store in VRAM\n");
  1954. printf(" -sm SPLIT_MODE, --split-mode SPLIT_MODE\n");
  1955. printf(" how to split the model across multiple GPUs, one of:\n");
  1956. printf(" - none: use one GPU only\n");
  1957. printf(" - layer (default): split layers and KV across GPUs\n");
  1958. printf(" - row: split rows across GPUs\n");
  1959. printf(" -ts SPLIT --tensor-split SPLIT\n");
  1960. printf(" fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1\n");
  1961. printf(" -mg i, --main-gpu i the GPU to use for the model (with split-mode = none),\n");
  1962. printf(" or for intermediate results and KV (with split-mode = row)\n");
  1963. printf(" -nkvo, --no-kv-offload\n");
  1964. printf(" disable KV offload\n");
  1965. }
  1966. printf(" -m FNAME, --model FNAME\n");
  1967. printf(" model path (default: models/$filename with filename from --hf-file or --model-url if set, otherwise %s)\n", DEFAULT_MODEL_PATH);
  1968. printf(" -mu MODEL_URL, --model-url MODEL_URL\n");
  1969. printf(" model download url (default: unused)\n");
  1970. printf(" -hfr REPO, --hf-repo REPO\n");
  1971. printf(" Hugging Face model repository (default: unused)\n");
  1972. printf(" -hff FILE, --hf-file FILE\n");
  1973. printf(" Hugging Face model file (default: unused)\n");
  1974. printf(" -a ALIAS, --alias ALIAS\n");
  1975. printf(" set an alias for the model, will be added as `model` field in completion response\n");
  1976. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  1977. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  1978. printf(" --host ip address to listen (default (default: %s)\n", sparams.hostname.c_str());
  1979. printf(" --port PORT port to listen (default (default: %d)\n", sparams.port);
  1980. printf(" --path PUBLIC_PATH path from which to serve static files (default: disabled)\n");
  1981. printf(" --api-key API_KEY optional api key to enhance server security. If set, requests must include this key for access.\n");
  1982. 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");
  1983. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1984. printf(" --ssl-key-file FNAME path to file a PEM-encoded SSL private key\n");
  1985. printf(" --ssl-cert-file FNAME path to file a PEM-encoded SSL certificate\n");
  1986. #endif
  1987. printf(" -to N, --timeout N server read/write timeout in seconds (default: %d)\n", sparams.read_timeout);
  1988. printf(" --embeddings enable embedding vector output (default: %s)\n", params.embedding ? "enabled" : "disabled");
  1989. printf(" -np N, --parallel N number of slots for process requests (default: %d)\n", params.n_parallel);
  1990. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: enabled)\n");
  1991. printf(" -fa, --flash-attn enable Flash Attention (default: %s)\n", params.flash_attn ? "enabled" : "disabled");
  1992. printf(" -spf FNAME, --system-prompt-file FNAME\n");
  1993. printf(" set a file to load a system prompt (initial prompt of all slots), this is useful for chat applications.\n");
  1994. printf(" -ctk TYPE, --cache-type-k TYPE\n");
  1995. printf(" KV cache data type for K (default: f16)\n");
  1996. printf(" -ctv TYPE, --cache-type-v TYPE\n");
  1997. printf(" KV cache data type for V (default: f16)\n");
  1998. printf(" --log-format log output format: json or text (default: json)\n");
  1999. printf(" --log-disable disables logging to a file.\n");
  2000. printf(" --slots-endpoint-disable disables slots monitoring endpoint.\n");
  2001. printf(" --metrics enable prometheus compatible metrics endpoint (default: %s).\n", sparams.metrics_endpoint ? "enabled" : "disabled");
  2002. printf(" --slot-save-path PATH path to save slot kv cache (default: disabled)\n");
  2003. printf("\n");
  2004. printf(" -n, --n-predict maximum tokens to predict (default: %d)\n", params.n_predict);
  2005. printf(" --override-kv KEY=TYPE:VALUE\n");
  2006. printf(" advanced option to override model metadata by key. may be specified multiple times.\n");
  2007. printf(" types: int, float, bool, str. example: --override-kv tokenizer.ggml.add_bos_token=bool:false\n");
  2008. 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");
  2009. 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");
  2010. printf(" --chat-template JINJA_TEMPLATE\n");
  2011. printf(" set custom jinja chat template (default: template taken from model's metadata)\n");
  2012. printf(" only commonly used templates are accepted:\n");
  2013. printf(" https://github.com/ggerganov/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template\n");
  2014. printf("\n");
  2015. }
  2016. static void server_params_parse(int argc, char ** argv, server_params & sparams, gpt_params & params) {
  2017. gpt_params default_params;
  2018. server_params default_sparams;
  2019. std::string arg;
  2020. bool invalid_param = false;
  2021. for (int i = 1; i < argc; i++) {
  2022. arg = argv[i];
  2023. if (arg == "--port") {
  2024. if (++i >= argc) {
  2025. invalid_param = true;
  2026. break;
  2027. }
  2028. sparams.port = std::stoi(argv[i]);
  2029. } else if (arg == "--host") {
  2030. if (++i >= argc) {
  2031. invalid_param = true;
  2032. break;
  2033. }
  2034. sparams.hostname = argv[i];
  2035. } else if (arg == "--path") {
  2036. if (++i >= argc) {
  2037. invalid_param = true;
  2038. break;
  2039. }
  2040. sparams.public_path = argv[i];
  2041. } else if (arg == "--api-key") {
  2042. if (++i >= argc) {
  2043. invalid_param = true;
  2044. break;
  2045. }
  2046. sparams.api_keys.push_back(argv[i]);
  2047. } else if (arg == "--api-key-file") {
  2048. if (++i >= argc) {
  2049. invalid_param = true;
  2050. break;
  2051. }
  2052. std::ifstream key_file(argv[i]);
  2053. if (!key_file) {
  2054. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  2055. invalid_param = true;
  2056. break;
  2057. }
  2058. std::string key;
  2059. while (std::getline(key_file, key)) {
  2060. if (key.size() > 0) {
  2061. sparams.api_keys.push_back(key);
  2062. }
  2063. }
  2064. key_file.close();
  2065. }
  2066. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2067. else if (arg == "--ssl-key-file") {
  2068. if (++i >= argc) {
  2069. invalid_param = true;
  2070. break;
  2071. }
  2072. sparams.ssl_key_file = argv[i];
  2073. } else if (arg == "--ssl-cert-file") {
  2074. if (++i >= argc) {
  2075. invalid_param = true;
  2076. break;
  2077. }
  2078. sparams.ssl_cert_file = argv[i];
  2079. }
  2080. #endif
  2081. else if (arg == "--timeout" || arg == "-to") {
  2082. if (++i >= argc) {
  2083. invalid_param = true;
  2084. break;
  2085. }
  2086. sparams.read_timeout = std::stoi(argv[i]);
  2087. sparams.write_timeout = std::stoi(argv[i]);
  2088. } else if (arg == "-m" || arg == "--model") {
  2089. if (++i >= argc) {
  2090. invalid_param = true;
  2091. break;
  2092. }
  2093. params.model = argv[i];
  2094. } else if (arg == "-mu" || arg == "--model-url") {
  2095. if (++i >= argc) {
  2096. invalid_param = true;
  2097. break;
  2098. }
  2099. params.model_url = argv[i];
  2100. } else if (arg == "-hfr" || arg == "--hf-repo") {
  2101. if (++i >= argc) {
  2102. invalid_param = true;
  2103. break;
  2104. }
  2105. params.hf_repo = argv[i];
  2106. } else if (arg == "-hff" || arg == "--hf-file") {
  2107. if (++i >= argc) {
  2108. invalid_param = true;
  2109. break;
  2110. }
  2111. params.hf_file = argv[i];
  2112. } else if (arg == "-a" || arg == "--alias") {
  2113. if (++i >= argc) {
  2114. invalid_param = true;
  2115. break;
  2116. }
  2117. params.model_alias = argv[i];
  2118. } else if (arg == "-h" || arg == "--help") {
  2119. server_print_usage(argv[0], default_params, default_sparams);
  2120. exit(0);
  2121. } else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size") {
  2122. if (++i >= argc) {
  2123. invalid_param = true;
  2124. break;
  2125. }
  2126. params.n_ctx = std::stoi(argv[i]);
  2127. } else if (arg == "--rope-scaling") {
  2128. if (++i >= argc) {
  2129. invalid_param = true;
  2130. break;
  2131. }
  2132. std::string value(argv[i]);
  2133. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE; }
  2134. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_LINEAR; }
  2135. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_YARN; }
  2136. else { invalid_param = true; break; }
  2137. } else if (arg == "--rope-freq-base") {
  2138. if (++i >= argc) {
  2139. invalid_param = true;
  2140. break;
  2141. }
  2142. params.rope_freq_base = std::stof(argv[i]);
  2143. } else if (arg == "--rope-freq-scale") {
  2144. if (++i >= argc) {
  2145. invalid_param = true;
  2146. break;
  2147. }
  2148. params.rope_freq_scale = std::stof(argv[i]);
  2149. } else if (arg == "--yarn-ext-factor") {
  2150. if (++i >= argc) {
  2151. invalid_param = true;
  2152. break;
  2153. }
  2154. params.yarn_ext_factor = std::stof(argv[i]);
  2155. }
  2156. else if (arg == "--yarn-attn-factor") {
  2157. if (++i >= argc) {
  2158. invalid_param = true;
  2159. break;
  2160. }
  2161. params.yarn_attn_factor = std::stof(argv[i]);
  2162. } else if (arg == "--yarn-beta-fast") {
  2163. if (++i >= argc) {
  2164. invalid_param = true;
  2165. break;
  2166. }
  2167. params.yarn_beta_fast = std::stof(argv[i]);
  2168. } else if (arg == "--yarn-beta-slow") {
  2169. if (++i >= argc) {
  2170. invalid_param = true;
  2171. break;
  2172. }
  2173. params.yarn_beta_slow = std::stof(argv[i]);
  2174. } else if (arg == "--pooling") {
  2175. if (++i >= argc) {
  2176. invalid_param = true;
  2177. break;
  2178. }
  2179. std::string value(argv[i]);
  2180. /**/ if (value == "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
  2181. else if (value == "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
  2182. else if (value == "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
  2183. else { invalid_param = true; break; }
  2184. } else if (arg == "--defrag-thold" || arg == "-dt") {
  2185. if (++i >= argc) {
  2186. invalid_param = true;
  2187. break;
  2188. }
  2189. params.defrag_thold = std::stof(argv[i]);
  2190. } else if (arg == "--threads" || arg == "-t") {
  2191. if (++i >= argc)
  2192. {
  2193. invalid_param = true;
  2194. break;
  2195. }
  2196. params.n_threads = std::stoi(argv[i]);
  2197. } else if (arg == "--grp-attn-n" || arg == "-gan") {
  2198. if (++i >= argc) {
  2199. invalid_param = true;
  2200. break;
  2201. }
  2202. params.grp_attn_n = std::stoi(argv[i]);
  2203. } else if (arg == "--grp-attn-w" || arg == "-gaw") {
  2204. if (++i >= argc) {
  2205. invalid_param = true;
  2206. break;
  2207. }
  2208. params.grp_attn_w = std::stoi(argv[i]);
  2209. } else if (arg == "--threads-batch" || arg == "-tb") {
  2210. if (++i >= argc) {
  2211. invalid_param = true;
  2212. break;
  2213. }
  2214. params.n_threads_batch = std::stoi(argv[i]);
  2215. } else if (arg == "--threads-http") {
  2216. if (++i >= argc) {
  2217. invalid_param = true;
  2218. break;
  2219. }
  2220. sparams.n_threads_http = std::stoi(argv[i]);
  2221. } else if (arg == "-b" || arg == "--batch-size") {
  2222. if (++i >= argc) {
  2223. invalid_param = true;
  2224. break;
  2225. }
  2226. params.n_batch = std::stoi(argv[i]);
  2227. } else if (arg == "-ub" || arg == "--ubatch-size") {
  2228. if (++i >= argc) {
  2229. invalid_param = true;
  2230. break;
  2231. }
  2232. params.n_ubatch = std::stoi(argv[i]);
  2233. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  2234. if (++i >= argc) {
  2235. invalid_param = true;
  2236. break;
  2237. }
  2238. if (llama_supports_gpu_offload()) {
  2239. params.n_gpu_layers = std::stoi(argv[i]);
  2240. } else {
  2241. LOG_WARNING(
  2242. "Not compiled with GPU offload support, --n-gpu-layers option will be ignored. "
  2243. "See main README.md for information on enabling GPU BLAS support",
  2244. {{"n_gpu_layers", params.n_gpu_layers}});
  2245. }
  2246. } else if (arg == "-nkvo" || arg == "--no-kv-offload") {
  2247. params.no_kv_offload = true;
  2248. } else if (arg == "--split-mode" || arg == "-sm") {
  2249. if (++i >= argc) {
  2250. invalid_param = true;
  2251. break;
  2252. }
  2253. std::string arg_next = argv[i];
  2254. if (arg_next == "none") {
  2255. params.split_mode = LLAMA_SPLIT_MODE_NONE;
  2256. } else if (arg_next == "layer") {
  2257. params.split_mode = LLAMA_SPLIT_MODE_LAYER;
  2258. } else if (arg_next == "row") {
  2259. params.split_mode = LLAMA_SPLIT_MODE_ROW;
  2260. } else {
  2261. invalid_param = true;
  2262. break;
  2263. }
  2264. #ifndef GGML_USE_CUDA
  2265. fprintf(stderr, "warning: llama.cpp was compiled without CUDA. Setting the split mode has no effect.\n");
  2266. #endif // GGML_USE_CUDA
  2267. } else if (arg == "--tensor-split" || arg == "-ts") {
  2268. if (++i >= argc) {
  2269. invalid_param = true;
  2270. break;
  2271. }
  2272. #if defined(GGML_USE_CUDA) || defined(GGML_USE_SYCL)
  2273. std::string arg_next = argv[i];
  2274. // split string by , and /
  2275. const std::regex regex{R"([,/]+)"};
  2276. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  2277. std::vector<std::string> split_arg{it, {}};
  2278. GGML_ASSERT(split_arg.size() <= llama_max_devices());
  2279. for (size_t i_device = 0; i_device < llama_max_devices(); ++i_device) {
  2280. if (i_device < split_arg.size()) {
  2281. params.tensor_split[i_device] = std::stof(split_arg[i_device]);
  2282. } else {
  2283. params.tensor_split[i_device] = 0.0f;
  2284. }
  2285. }
  2286. #else
  2287. LOG_WARNING("llama.cpp was compiled without CUDA. It is not possible to set a tensor split.\n", {});
  2288. #endif // GGML_USE_CUDA
  2289. } else if (arg == "--main-gpu" || arg == "-mg") {
  2290. if (++i >= argc) {
  2291. invalid_param = true;
  2292. break;
  2293. }
  2294. #if defined(GGML_USE_CUDA) || defined(GGML_USE_SYCL)
  2295. params.main_gpu = std::stoi(argv[i]);
  2296. #else
  2297. LOG_WARNING("llama.cpp was compiled without CUDA. It is not possible to set a main GPU.", {});
  2298. #endif
  2299. } else if (arg == "--lora") {
  2300. if (++i >= argc) {
  2301. invalid_param = true;
  2302. break;
  2303. }
  2304. params.lora_adapter.emplace_back(argv[i], 1.0f);
  2305. params.use_mmap = false;
  2306. } else if (arg == "--lora-scaled") {
  2307. if (++i >= argc) {
  2308. invalid_param = true;
  2309. break;
  2310. }
  2311. const char * lora_adapter = argv[i];
  2312. if (++i >= argc) {
  2313. invalid_param = true;
  2314. break;
  2315. }
  2316. params.lora_adapter.emplace_back(lora_adapter, std::stof(argv[i]));
  2317. params.use_mmap = false;
  2318. } else if (arg == "--lora-base") {
  2319. if (++i >= argc) {
  2320. invalid_param = true;
  2321. break;
  2322. }
  2323. params.lora_base = argv[i];
  2324. } else if (arg == "-v" || arg == "--verbose") {
  2325. #if SERVER_VERBOSE != 1
  2326. LOG_WARNING("server.cpp is not built with verbose logging.", {});
  2327. #else
  2328. server_verbose = true;
  2329. #endif
  2330. } else if (arg == "--mlock") {
  2331. params.use_mlock = true;
  2332. } else if (arg == "--no-mmap") {
  2333. params.use_mmap = false;
  2334. } else if (arg == "--numa") {
  2335. if (++i >= argc) {
  2336. invalid_param = true;
  2337. break;
  2338. } else {
  2339. std::string value(argv[i]);
  2340. /**/ if (value == "distribute" || value == "" ) { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
  2341. else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
  2342. else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
  2343. else { invalid_param = true; break; }
  2344. }
  2345. } else if (arg == "--embedding" || arg == "--embeddings") {
  2346. params.embedding = true;
  2347. } else if (arg == "-cb" || arg == "--cont-batching") {
  2348. params.cont_batching = true;
  2349. } else if (arg == "-fa" || arg == "--flash-attn") {
  2350. params.flash_attn = true;
  2351. } else if (arg == "-np" || arg == "--parallel") {
  2352. if (++i >= argc) {
  2353. invalid_param = true;
  2354. break;
  2355. }
  2356. params.n_parallel = std::stoi(argv[i]);
  2357. } else if (arg == "-n" || arg == "--n-predict") {
  2358. if (++i >= argc) {
  2359. invalid_param = true;
  2360. break;
  2361. }
  2362. params.n_predict = std::stoi(argv[i]);
  2363. } else if (arg == "-spf" || arg == "--system-prompt-file") {
  2364. if (++i >= argc) {
  2365. invalid_param = true;
  2366. break;
  2367. }
  2368. std::ifstream file(argv[i]);
  2369. if (!file) {
  2370. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  2371. invalid_param = true;
  2372. break;
  2373. }
  2374. std::string system_prompt;
  2375. std::copy(
  2376. std::istreambuf_iterator<char>(file),
  2377. std::istreambuf_iterator<char>(),
  2378. std::back_inserter(system_prompt)
  2379. );
  2380. sparams.system_prompt = system_prompt;
  2381. } else if (arg == "-ctk" || arg == "--cache-type-k") {
  2382. params.cache_type_k = argv[++i];
  2383. } else if (arg == "-ctv" || arg == "--cache-type-v") {
  2384. params.cache_type_v = argv[++i];
  2385. } else if (arg == "--log-format") {
  2386. if (++i >= argc) {
  2387. invalid_param = true;
  2388. break;
  2389. }
  2390. if (std::strcmp(argv[i], "json") == 0) {
  2391. server_log_json = true;
  2392. } else if (std::strcmp(argv[i], "text") == 0) {
  2393. server_log_json = false;
  2394. } else {
  2395. invalid_param = true;
  2396. break;
  2397. }
  2398. } else if (arg == "--log-disable") {
  2399. log_set_target(stdout);
  2400. LOG_INFO("logging to file is disabled.", {});
  2401. } else if (arg == "--slots-endpoint-disable") {
  2402. sparams.slots_endpoint = false;
  2403. } else if (arg == "--metrics") {
  2404. sparams.metrics_endpoint = true;
  2405. } else if (arg == "--slot-save-path") {
  2406. if (++i >= argc) {
  2407. invalid_param = true;
  2408. break;
  2409. }
  2410. sparams.slot_save_path = argv[i];
  2411. // if doesn't end with DIRECTORY_SEPARATOR, add it
  2412. if (!sparams.slot_save_path.empty() && sparams.slot_save_path[sparams.slot_save_path.size() - 1] != DIRECTORY_SEPARATOR) {
  2413. sparams.slot_save_path += DIRECTORY_SEPARATOR;
  2414. }
  2415. } else if (arg == "--chat-template") {
  2416. if (++i >= argc) {
  2417. invalid_param = true;
  2418. break;
  2419. }
  2420. if (!verify_custom_template(argv[i])) {
  2421. fprintf(stderr, "error: the supplied chat template is not supported: %s\n", argv[i]);
  2422. fprintf(stderr, "note: llama.cpp does not use jinja parser, we only support commonly used templates\n");
  2423. invalid_param = true;
  2424. break;
  2425. }
  2426. sparams.chat_template = argv[i];
  2427. } else if (arg == "--override-kv") {
  2428. if (++i >= argc) {
  2429. invalid_param = true;
  2430. break;
  2431. }
  2432. if (!parse_kv_override(argv[i], params.kv_overrides)) {
  2433. fprintf(stderr, "error: Invalid type for KV override: %s\n", argv[i]);
  2434. invalid_param = true;
  2435. break;
  2436. }
  2437. } else {
  2438. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  2439. server_print_usage(argv[0], default_params, default_sparams);
  2440. exit(1);
  2441. }
  2442. }
  2443. gpt_params_handle_model_default(params);
  2444. if (!params.kv_overrides.empty()) {
  2445. params.kv_overrides.emplace_back();
  2446. params.kv_overrides.back().key[0] = 0;
  2447. }
  2448. if (invalid_param) {
  2449. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  2450. server_print_usage(argv[0], default_params, default_sparams);
  2451. exit(1);
  2452. }
  2453. }
  2454. static void log_server_request(const httplib::Request & req, const httplib::Response & res) {
  2455. // skip GH copilot requests when using default port
  2456. if (req.path == "/v1/health" || req.path == "/v1/completions") {
  2457. return;
  2458. }
  2459. LOG_INFO("request", {
  2460. {"remote_addr", req.remote_addr},
  2461. {"remote_port", req.remote_port},
  2462. {"status", res.status},
  2463. {"method", req.method},
  2464. {"path", req.path},
  2465. {"params", req.params},
  2466. });
  2467. LOG_VERBOSE("request", {
  2468. {"request", req.body},
  2469. {"response", res.body},
  2470. });
  2471. }
  2472. std::function<void(int)> shutdown_handler;
  2473. std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
  2474. inline void signal_handler(int signal) {
  2475. if (is_terminating.test_and_set()) {
  2476. // in case it hangs, we can force terminate the server by hitting Ctrl+C twice
  2477. // this is for better developer experience, we can remove when the server is stable enough
  2478. fprintf(stderr, "Received second interrupt, terminating immediately.\n");
  2479. exit(1);
  2480. }
  2481. shutdown_handler(signal);
  2482. }
  2483. int main(int argc, char ** argv) {
  2484. #if SERVER_VERBOSE != 1
  2485. log_disable();
  2486. #endif
  2487. // own arguments required by this example
  2488. gpt_params params;
  2489. server_params sparams;
  2490. // struct that contains llama context and inference
  2491. server_context ctx_server;
  2492. server_params_parse(argc, argv, sparams, params);
  2493. if (!sparams.system_prompt.empty()) {
  2494. ctx_server.system_prompt_set(json::parse(sparams.system_prompt));
  2495. }
  2496. if (params.model_alias == "unknown") {
  2497. params.model_alias = params.model;
  2498. }
  2499. llama_backend_init();
  2500. llama_numa_init(params.numa);
  2501. LOG_INFO("build info", {
  2502. {"build", LLAMA_BUILD_NUMBER},
  2503. {"commit", LLAMA_COMMIT}
  2504. });
  2505. LOG_INFO("system info", {
  2506. {"n_threads", params.n_threads},
  2507. {"n_threads_batch", params.n_threads_batch},
  2508. {"total_threads", std::thread::hardware_concurrency()},
  2509. {"system_info", llama_print_system_info()},
  2510. });
  2511. std::unique_ptr<httplib::Server> svr;
  2512. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2513. if (sparams.ssl_key_file != "" && sparams.ssl_cert_file != "") {
  2514. LOG_INFO("Running with SSL", {{"key", sparams.ssl_key_file}, {"cert", sparams.ssl_cert_file}});
  2515. svr.reset(
  2516. new httplib::SSLServer(sparams.ssl_cert_file.c_str(), sparams.ssl_key_file.c_str())
  2517. );
  2518. } else {
  2519. LOG_INFO("Running without SSL", {});
  2520. svr.reset(new httplib::Server());
  2521. }
  2522. #else
  2523. svr.reset(new httplib::Server());
  2524. #endif
  2525. std::atomic<server_state> state{SERVER_STATE_LOADING_MODEL};
  2526. svr->set_default_headers({{"Server", "llama.cpp"}});
  2527. // CORS preflight
  2528. svr->Options(R"(.*)", [](const httplib::Request & req, httplib::Response & res) {
  2529. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2530. res.set_header("Access-Control-Allow-Credentials", "true");
  2531. res.set_header("Access-Control-Allow-Methods", "POST");
  2532. res.set_header("Access-Control-Allow-Headers", "*");
  2533. return res.set_content("", "application/json; charset=utf-8");
  2534. });
  2535. svr->set_logger(log_server_request);
  2536. auto res_error = [](httplib::Response & res, json error_data) {
  2537. json final_response {{"error", error_data}};
  2538. res.set_content(final_response.dump(), "application/json; charset=utf-8");
  2539. res.status = json_value(error_data, "code", 500);
  2540. };
  2541. svr->set_exception_handler([&res_error](const httplib::Request &, httplib::Response & res, std::exception_ptr ep) {
  2542. std::string message;
  2543. try {
  2544. std::rethrow_exception(std::move(ep));
  2545. } catch (std::exception & e) {
  2546. message = e.what();
  2547. } catch (...) {
  2548. message = "Unknown Exception";
  2549. }
  2550. json formatted_error = format_error_response(message, ERROR_TYPE_SERVER);
  2551. LOG_VERBOSE("Got exception", formatted_error);
  2552. res_error(res, formatted_error);
  2553. });
  2554. svr->set_error_handler([&res_error](const httplib::Request &, httplib::Response & res) {
  2555. if (res.status == 404) {
  2556. res_error(res, format_error_response("File Not Found", ERROR_TYPE_NOT_FOUND));
  2557. }
  2558. // for other error codes, we skip processing here because it's already done by res_error()
  2559. });
  2560. // set timeouts and change hostname and port
  2561. svr->set_read_timeout (sparams.read_timeout);
  2562. svr->set_write_timeout(sparams.write_timeout);
  2563. if (!svr->bind_to_port(sparams.hostname, sparams.port)) {
  2564. fprintf(stderr, "\ncouldn't bind to server socket: hostname=%s port=%d\n\n", sparams.hostname.c_str(), sparams.port);
  2565. return 1;
  2566. }
  2567. std::unordered_map<std::string, std::string> log_data;
  2568. log_data["hostname"] = sparams.hostname;
  2569. log_data["port"] = std::to_string(sparams.port);
  2570. if (sparams.api_keys.size() == 1) {
  2571. auto key = sparams.api_keys[0];
  2572. log_data["api_key"] = "api_key: ****" + key.substr(std::max((int)(key.length() - 4), 0));
  2573. } else if (sparams.api_keys.size() > 1) {
  2574. log_data["api_key"] = "api_key: " + std::to_string(sparams.api_keys.size()) + " keys loaded";
  2575. }
  2576. // load the model
  2577. if (!ctx_server.load_model(params)) {
  2578. state.store(SERVER_STATE_ERROR);
  2579. return 1;
  2580. } else {
  2581. ctx_server.init();
  2582. state.store(SERVER_STATE_READY);
  2583. }
  2584. LOG_INFO("model loaded", {});
  2585. const auto model_meta = ctx_server.model_meta();
  2586. // if a custom chat template is not supplied, we will use the one that comes with the model (if any)
  2587. if (sparams.chat_template.empty()) {
  2588. if (!ctx_server.validate_model_chat_template()) {
  2589. 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", {});
  2590. sparams.chat_template = "chatml";
  2591. }
  2592. }
  2593. // print sample chat example to make it clear which template is used
  2594. {
  2595. json chat;
  2596. chat.push_back({{"role", "system"}, {"content", "You are a helpful assistant"}});
  2597. chat.push_back({{"role", "user"}, {"content", "Hello"}});
  2598. chat.push_back({{"role", "assistant"}, {"content", "Hi there"}});
  2599. chat.push_back({{"role", "user"}, {"content", "How are you?"}});
  2600. const std::string chat_example = format_chat(ctx_server.model, sparams.chat_template, chat);
  2601. LOG_INFO("chat template", {
  2602. {"chat_example", chat_example},
  2603. {"built_in", sparams.chat_template.empty()},
  2604. });
  2605. }
  2606. //
  2607. // Middlewares
  2608. //
  2609. auto middleware_validate_api_key = [&sparams, &res_error](const httplib::Request & req, httplib::Response & res) {
  2610. // TODO: should we apply API key to all endpoints, including "/health" and "/models"?
  2611. static const std::set<std::string> protected_endpoints = {
  2612. "/props",
  2613. "/completion",
  2614. "/completions",
  2615. "/v1/completions",
  2616. "/chat/completions",
  2617. "/v1/chat/completions",
  2618. "/infill",
  2619. "/tokenize",
  2620. "/detokenize",
  2621. "/embedding",
  2622. "/embeddings",
  2623. "/v1/embeddings",
  2624. };
  2625. // If API key is not set, skip validation
  2626. if (sparams.api_keys.empty()) {
  2627. return true;
  2628. }
  2629. // If path is not in protected_endpoints list, skip validation
  2630. if (protected_endpoints.find(req.path) == protected_endpoints.end()) {
  2631. return true;
  2632. }
  2633. // Check for API key in the header
  2634. auto auth_header = req.get_header_value("Authorization");
  2635. std::string prefix = "Bearer ";
  2636. if (auth_header.substr(0, prefix.size()) == prefix) {
  2637. std::string received_api_key = auth_header.substr(prefix.size());
  2638. if (std::find(sparams.api_keys.begin(), sparams.api_keys.end(), received_api_key) != sparams.api_keys.end()) {
  2639. return true; // API key is valid
  2640. }
  2641. }
  2642. // API key is invalid or not provided
  2643. // TODO: make another middleware for CORS related logic
  2644. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2645. res_error(res, format_error_response("Invalid API Key", ERROR_TYPE_AUTHENTICATION));
  2646. LOG_WARNING("Unauthorized: Invalid API Key", {});
  2647. return false;
  2648. };
  2649. // register server middlewares
  2650. svr->set_pre_routing_handler([&middleware_validate_api_key](const httplib::Request & req, httplib::Response & res) {
  2651. if (!middleware_validate_api_key(req, res)) {
  2652. return httplib::Server::HandlerResponse::Handled;
  2653. }
  2654. return httplib::Server::HandlerResponse::Unhandled;
  2655. });
  2656. //
  2657. // Route handlers (or controllers)
  2658. //
  2659. const auto handle_health = [&](const httplib::Request & req, httplib::Response & res) {
  2660. server_state current_state = state.load();
  2661. switch (current_state) {
  2662. case SERVER_STATE_READY:
  2663. {
  2664. // request slots data using task queue
  2665. server_task task;
  2666. task.id = ctx_server.queue_tasks.get_new_id();
  2667. task.type = SERVER_TASK_TYPE_METRICS;
  2668. task.id_target = -1;
  2669. ctx_server.queue_results.add_waiting_task_id(task.id);
  2670. ctx_server.queue_tasks.post(task);
  2671. // get the result
  2672. server_task_result result = ctx_server.queue_results.recv(task.id);
  2673. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2674. const int n_idle_slots = result.data["idle"];
  2675. const int n_processing_slots = result.data["processing"];
  2676. json health = {
  2677. {"status", "ok"},
  2678. {"slots_idle", n_idle_slots},
  2679. {"slots_processing", n_processing_slots}
  2680. };
  2681. res.status = 200; // HTTP OK
  2682. if (sparams.slots_endpoint && req.has_param("include_slots")) {
  2683. health["slots"] = result.data["slots"];
  2684. }
  2685. if (n_idle_slots == 0) {
  2686. health["status"] = "no slot available";
  2687. if (req.has_param("fail_on_no_slot")) {
  2688. res.status = 503; // HTTP Service Unavailable
  2689. }
  2690. }
  2691. res.set_content(health.dump(), "application/json");
  2692. break;
  2693. }
  2694. case SERVER_STATE_LOADING_MODEL:
  2695. {
  2696. res_error(res, format_error_response("Loading model", ERROR_TYPE_UNAVAILABLE));
  2697. } break;
  2698. case SERVER_STATE_ERROR:
  2699. {
  2700. res_error(res, format_error_response("Model failed to load", ERROR_TYPE_SERVER));
  2701. } break;
  2702. }
  2703. };
  2704. const auto handle_slots = [&](const httplib::Request &, httplib::Response & res) {
  2705. if (!sparams.slots_endpoint) {
  2706. res_error(res, format_error_response("This server does not support slots endpoint.", ERROR_TYPE_NOT_SUPPORTED));
  2707. return;
  2708. }
  2709. // request slots data using task queue
  2710. server_task task;
  2711. task.id = ctx_server.queue_tasks.get_new_id();
  2712. task.id_multi = -1;
  2713. task.id_target = -1;
  2714. task.type = SERVER_TASK_TYPE_METRICS;
  2715. ctx_server.queue_results.add_waiting_task_id(task.id);
  2716. ctx_server.queue_tasks.post(task);
  2717. // get the result
  2718. server_task_result result = ctx_server.queue_results.recv(task.id);
  2719. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2720. res.set_content(result.data["slots"].dump(), "application/json");
  2721. res.status = 200; // HTTP OK
  2722. };
  2723. const auto handle_metrics = [&](const httplib::Request &, httplib::Response & res) {
  2724. if (!sparams.metrics_endpoint) {
  2725. res_error(res, format_error_response("This server does not support metrics endpoint.", ERROR_TYPE_NOT_SUPPORTED));
  2726. return;
  2727. }
  2728. // request slots data using task queue
  2729. server_task task;
  2730. task.id = ctx_server.queue_tasks.get_new_id();
  2731. task.id_multi = -1;
  2732. task.id_target = -1;
  2733. task.type = SERVER_TASK_TYPE_METRICS;
  2734. task.data.push_back({{"reset_bucket", true}});
  2735. ctx_server.queue_results.add_waiting_task_id(task.id);
  2736. ctx_server.queue_tasks.post(task);
  2737. // get the result
  2738. server_task_result result = ctx_server.queue_results.recv(task.id);
  2739. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2740. json data = result.data;
  2741. const uint64_t n_prompt_tokens_processed = data["n_prompt_tokens_processed"];
  2742. const uint64_t t_prompt_processing = data["t_prompt_processing"];
  2743. const uint64_t n_tokens_predicted = data["n_tokens_predicted"];
  2744. const uint64_t t_tokens_generation = data["t_tokens_generation"];
  2745. const int32_t kv_cache_used_cells = data["kv_cache_used_cells"];
  2746. // metrics definition: https://prometheus.io/docs/practices/naming/#metric-names
  2747. json all_metrics_def = json {
  2748. {"counter", {{
  2749. {"name", "prompt_tokens_total"},
  2750. {"help", "Number of prompt tokens processed."},
  2751. {"value", (uint64_t) data["n_prompt_tokens_processed_total"]}
  2752. }, {
  2753. {"name", "prompt_seconds_total"},
  2754. {"help", "Prompt process time"},
  2755. {"value", (uint64_t) data["t_prompt_processing_total"] / 1.e3}
  2756. }, {
  2757. {"name", "tokens_predicted_total"},
  2758. {"help", "Number of generation tokens processed."},
  2759. {"value", (uint64_t) data["n_tokens_predicted_total"]}
  2760. }, {
  2761. {"name", "tokens_predicted_seconds_total"},
  2762. {"help", "Predict process time"},
  2763. {"value", (uint64_t) data["t_tokens_generation_total"] / 1.e3}
  2764. }}},
  2765. {"gauge", {{
  2766. {"name", "prompt_tokens_seconds"},
  2767. {"help", "Average prompt throughput in tokens/s."},
  2768. {"value", n_prompt_tokens_processed ? 1.e3 / t_prompt_processing * n_prompt_tokens_processed : 0.}
  2769. },{
  2770. {"name", "predicted_tokens_seconds"},
  2771. {"help", "Average generation throughput in tokens/s."},
  2772. {"value", n_tokens_predicted ? 1.e3 / t_tokens_generation * n_tokens_predicted : 0.}
  2773. },{
  2774. {"name", "kv_cache_usage_ratio"},
  2775. {"help", "KV-cache usage. 1 means 100 percent usage."},
  2776. {"value", 1. * kv_cache_used_cells / params.n_ctx}
  2777. },{
  2778. {"name", "kv_cache_tokens"},
  2779. {"help", "KV-cache tokens."},
  2780. {"value", (uint64_t) data["kv_cache_tokens_count"]}
  2781. },{
  2782. {"name", "requests_processing"},
  2783. {"help", "Number of request processing."},
  2784. {"value", (uint64_t) data["processing"]}
  2785. },{
  2786. {"name", "requests_deferred"},
  2787. {"help", "Number of request deferred."},
  2788. {"value", (uint64_t) data["deferred"]}
  2789. }}}
  2790. };
  2791. std::stringstream prometheus;
  2792. for (const auto & el : all_metrics_def.items()) {
  2793. const auto & type = el.key();
  2794. const auto & metrics_def = el.value();
  2795. for (const auto & metric_def : metrics_def) {
  2796. const std::string name = metric_def["name"];
  2797. const std::string help = metric_def["help"];
  2798. auto value = json_value(metric_def, "value", 0.);
  2799. prometheus << "# HELP llamacpp:" << name << " " << help << "\n"
  2800. << "# TYPE llamacpp:" << name << " " << type << "\n"
  2801. << "llamacpp:" << name << " " << value << "\n";
  2802. }
  2803. }
  2804. const int64_t t_start = data["t_start"];
  2805. res.set_header("Process-Start-Time-Unix", std::to_string(t_start));
  2806. res.set_content(prometheus.str(), "text/plain; version=0.0.4");
  2807. res.status = 200; // HTTP OK
  2808. };
  2809. const auto handle_slots_save = [&ctx_server, &res_error, &sparams](const httplib::Request & req, httplib::Response & res, int id_slot) {
  2810. json request_data = json::parse(req.body);
  2811. std::string filename = request_data["filename"];
  2812. if (!validate_file_name(filename)) {
  2813. res_error(res, format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  2814. return;
  2815. }
  2816. std::string filepath = sparams.slot_save_path + filename;
  2817. server_task task;
  2818. task.type = SERVER_TASK_TYPE_SLOT_SAVE;
  2819. task.data = {
  2820. { "id_slot", id_slot },
  2821. { "filename", filename },
  2822. { "filepath", filepath }
  2823. };
  2824. const int id_task = ctx_server.queue_tasks.post(task);
  2825. ctx_server.queue_results.add_waiting_task_id(id_task);
  2826. server_task_result result = ctx_server.queue_results.recv(id_task);
  2827. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2828. if (result.error) {
  2829. res_error(res, result.data);
  2830. } else {
  2831. res.set_content(result.data.dump(), "application/json");
  2832. }
  2833. };
  2834. const auto handle_slots_restore = [&ctx_server, &res_error, &sparams](const httplib::Request & req, httplib::Response & res, int id_slot) {
  2835. json request_data = json::parse(req.body);
  2836. std::string filename = request_data["filename"];
  2837. if (!validate_file_name(filename)) {
  2838. res_error(res, format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  2839. return;
  2840. }
  2841. std::string filepath = sparams.slot_save_path + filename;
  2842. server_task task;
  2843. task.type = SERVER_TASK_TYPE_SLOT_RESTORE;
  2844. task.data = {
  2845. { "id_slot", id_slot },
  2846. { "filename", filename },
  2847. { "filepath", filepath }
  2848. };
  2849. const int id_task = ctx_server.queue_tasks.post(task);
  2850. ctx_server.queue_results.add_waiting_task_id(id_task);
  2851. server_task_result result = ctx_server.queue_results.recv(id_task);
  2852. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2853. if (result.error) {
  2854. res_error(res, result.data);
  2855. } else {
  2856. res.set_content(result.data.dump(), "application/json");
  2857. }
  2858. };
  2859. const auto handle_slots_erase = [&ctx_server, &res_error](const httplib::Request & /* req */, httplib::Response & res, int id_slot) {
  2860. server_task task;
  2861. task.type = SERVER_TASK_TYPE_SLOT_ERASE;
  2862. task.data = {
  2863. { "id_slot", id_slot },
  2864. };
  2865. const int id_task = ctx_server.queue_tasks.post(task);
  2866. ctx_server.queue_results.add_waiting_task_id(id_task);
  2867. server_task_result result = ctx_server.queue_results.recv(id_task);
  2868. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2869. if (result.error) {
  2870. res_error(res, result.data);
  2871. } else {
  2872. res.set_content(result.data.dump(), "application/json");
  2873. }
  2874. };
  2875. const auto handle_slots_action = [&res_error, &handle_slots_save, &handle_slots_restore, &handle_slots_erase](const httplib::Request & req, httplib::Response & res) {
  2876. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2877. std::string id_slot_str = req.path_params.at("id_slot");
  2878. int id_slot;
  2879. try {
  2880. id_slot = std::stoi(id_slot_str);
  2881. } catch (const std::exception &) {
  2882. res_error(res, format_error_response("Invalid slot ID", ERROR_TYPE_INVALID_REQUEST));
  2883. return;
  2884. }
  2885. std::string action = req.get_param_value("action");
  2886. if (action == "save") {
  2887. handle_slots_save(req, res, id_slot);
  2888. } else if (action == "restore") {
  2889. handle_slots_restore(req, res, id_slot);
  2890. } else if (action == "erase") {
  2891. handle_slots_erase(req, res, id_slot);
  2892. } else {
  2893. res_error(res, format_error_response("Invalid action", ERROR_TYPE_INVALID_REQUEST));
  2894. }
  2895. };
  2896. const auto handle_props = [&ctx_server](const httplib::Request & req, httplib::Response & res) {
  2897. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2898. json data = {
  2899. { "user_name", ctx_server.name_user.c_str() },
  2900. { "assistant_name", ctx_server.name_assistant.c_str() },
  2901. { "default_generation_settings", ctx_server.default_generation_settings_for_props },
  2902. { "total_slots", ctx_server.params.n_parallel }
  2903. };
  2904. res.set_content(data.dump(), "application/json; charset=utf-8");
  2905. };
  2906. const auto handle_completions = [&ctx_server, &res_error](const httplib::Request & req, httplib::Response & res) {
  2907. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2908. json data = json::parse(req.body);
  2909. const int id_task = ctx_server.queue_tasks.get_new_id();
  2910. ctx_server.queue_results.add_waiting_task_id(id_task);
  2911. ctx_server.request_completion(id_task, -1, data, false, false);
  2912. if (!json_value(data, "stream", false)) {
  2913. server_task_result result = ctx_server.queue_results.recv(id_task);
  2914. if (!result.error && result.stop) {
  2915. res.set_content(result.data.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  2916. } else {
  2917. res_error(res, result.data);
  2918. }
  2919. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2920. } else {
  2921. const auto chunked_content_provider = [id_task, &ctx_server](size_t, httplib::DataSink & sink) {
  2922. while (true) {
  2923. server_task_result result = ctx_server.queue_results.recv(id_task);
  2924. if (!result.error) {
  2925. const std::string str =
  2926. "data: " +
  2927. result.data.dump(-1, ' ', false, json::error_handler_t::replace) +
  2928. "\n\n";
  2929. LOG_VERBOSE("data stream", {
  2930. { "to_send", str }
  2931. });
  2932. if (!sink.write(str.c_str(), str.size())) {
  2933. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2934. return false;
  2935. }
  2936. if (result.stop) {
  2937. break;
  2938. }
  2939. } else {
  2940. const std::string str =
  2941. "error: " +
  2942. result.data.dump(-1, ' ', false, json::error_handler_t::replace) +
  2943. "\n\n";
  2944. LOG_VERBOSE("data stream", {
  2945. { "to_send", str }
  2946. });
  2947. if (!sink.write(str.c_str(), str.size())) {
  2948. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2949. return false;
  2950. }
  2951. break;
  2952. }
  2953. }
  2954. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2955. sink.done();
  2956. return true;
  2957. };
  2958. auto on_complete = [id_task, &ctx_server] (bool) {
  2959. // cancel
  2960. ctx_server.request_cancel(id_task);
  2961. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2962. };
  2963. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2964. }
  2965. };
  2966. const auto handle_models = [&params, &model_meta](const httplib::Request & req, httplib::Response & res) {
  2967. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2968. json models = {
  2969. {"object", "list"},
  2970. {"data", {
  2971. {
  2972. {"id", params.model_alias},
  2973. {"object", "model"},
  2974. {"created", std::time(0)},
  2975. {"owned_by", "llamacpp"},
  2976. {"meta", model_meta}
  2977. },
  2978. }}
  2979. };
  2980. res.set_content(models.dump(), "application/json; charset=utf-8");
  2981. };
  2982. const auto handle_chat_completions = [&ctx_server, &sparams, &res_error](const httplib::Request & req, httplib::Response & res) {
  2983. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2984. json data = oaicompat_completion_params_parse(ctx_server.model, json::parse(req.body), sparams.chat_template);
  2985. const int id_task = ctx_server.queue_tasks.get_new_id();
  2986. ctx_server.queue_results.add_waiting_task_id(id_task);
  2987. ctx_server.request_completion(id_task, -1, data, false, false);
  2988. const auto completion_id = gen_chatcmplid();
  2989. if (!json_value(data, "stream", false)) {
  2990. server_task_result result = ctx_server.queue_results.recv(id_task);
  2991. if (!result.error && result.stop) {
  2992. json result_oai = format_final_response_oaicompat(data, result.data, completion_id);
  2993. res.set_content(result_oai.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  2994. } else {
  2995. res_error(res, result.data);
  2996. }
  2997. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2998. } else {
  2999. const auto chunked_content_provider = [id_task, &ctx_server, completion_id](size_t, httplib::DataSink & sink) {
  3000. while (true) {
  3001. server_task_result result = ctx_server.queue_results.recv(id_task);
  3002. if (!result.error) {
  3003. std::vector<json> result_array = format_partial_response_oaicompat(result.data, completion_id);
  3004. for (auto it = result_array.begin(); it != result_array.end(); ++it) {
  3005. if (!it->empty()) {
  3006. const std::string str =
  3007. "data: " +
  3008. it->dump(-1, ' ', false, json::error_handler_t::replace) +
  3009. "\n\n";
  3010. LOG_VERBOSE("data stream", {{"to_send", str}});
  3011. if (!sink.write(str.c_str(), str.size())) {
  3012. ctx_server.queue_results.remove_waiting_task_id(id_task);
  3013. return false;
  3014. }
  3015. }
  3016. }
  3017. if (result.stop) {
  3018. break;
  3019. }
  3020. } else {
  3021. const std::string str =
  3022. "error: " +
  3023. result.data.dump(-1, ' ', false, json::error_handler_t::replace) +
  3024. "\n\n";
  3025. LOG_VERBOSE("data stream", {{"to_send", str}});
  3026. if (!sink.write(str.c_str(), str.size())) {
  3027. ctx_server.queue_results.remove_waiting_task_id(id_task);
  3028. return false;
  3029. }
  3030. break;
  3031. }
  3032. }
  3033. sink.done();
  3034. ctx_server.queue_results.remove_waiting_task_id(id_task);
  3035. return true;
  3036. };
  3037. auto on_complete = [id_task, &ctx_server](bool) {
  3038. // cancel request
  3039. ctx_server.request_cancel(id_task);
  3040. ctx_server.queue_results.remove_waiting_task_id(id_task);
  3041. };
  3042. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  3043. }
  3044. };
  3045. const auto handle_infill = [&ctx_server, &res_error](const httplib::Request & req, httplib::Response & res) {
  3046. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  3047. json data = json::parse(req.body);
  3048. const int id_task = ctx_server.queue_tasks.get_new_id();
  3049. ctx_server.queue_results.add_waiting_task_id(id_task);
  3050. ctx_server.request_completion(id_task, -1, data, true, false);
  3051. if (!json_value(data, "stream", false)) {
  3052. server_task_result result = ctx_server.queue_results.recv(id_task);
  3053. if (!result.error && result.stop) {
  3054. res.set_content(result.data.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  3055. } else {
  3056. res_error(res, result.data);
  3057. }
  3058. ctx_server.queue_results.remove_waiting_task_id(id_task);
  3059. } else {
  3060. const auto chunked_content_provider = [id_task, &ctx_server](size_t, httplib::DataSink & sink) {
  3061. while (true) {
  3062. server_task_result result = ctx_server.queue_results.recv(id_task);
  3063. if (!result.error) {
  3064. const std::string str =
  3065. "data: " +
  3066. result.data.dump(-1, ' ', false, json::error_handler_t::replace) +
  3067. "\n\n";
  3068. LOG_VERBOSE("data stream", {
  3069. { "to_send", str }
  3070. });
  3071. if (!sink.write(str.c_str(), str.size())) {
  3072. ctx_server.queue_results.remove_waiting_task_id(id_task);
  3073. return false;
  3074. }
  3075. if (result.stop) {
  3076. break;
  3077. }
  3078. } else {
  3079. break;
  3080. }
  3081. }
  3082. ctx_server.queue_results.remove_waiting_task_id(id_task);
  3083. sink.done();
  3084. return true;
  3085. };
  3086. auto on_complete = [id_task, &ctx_server] (bool) {
  3087. ctx_server.request_cancel(id_task);
  3088. };
  3089. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  3090. }
  3091. };
  3092. const auto handle_tokenize = [&ctx_server](const httplib::Request & req, httplib::Response & res) {
  3093. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  3094. const json body = json::parse(req.body);
  3095. std::vector<llama_token> tokens;
  3096. if (body.count("content") != 0) {
  3097. const bool add_special = json_value(body, "add_special", false);
  3098. tokens = ctx_server.tokenize(body["content"], add_special);
  3099. }
  3100. const json data = format_tokenizer_response(tokens);
  3101. return res.set_content(data.dump(), "application/json; charset=utf-8");
  3102. };
  3103. const auto handle_detokenize = [&ctx_server](const httplib::Request & req, httplib::Response & res) {
  3104. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  3105. const json body = json::parse(req.body);
  3106. std::string content;
  3107. if (body.count("tokens") != 0) {
  3108. const std::vector<llama_token> tokens = body["tokens"];
  3109. content = tokens_to_str(ctx_server.ctx, tokens.cbegin(), tokens.cend());
  3110. }
  3111. const json data = format_detokenized_response(content);
  3112. return res.set_content(data.dump(), "application/json; charset=utf-8");
  3113. };
  3114. const auto handle_embeddings = [&params, &ctx_server, &res_error](const httplib::Request & req, httplib::Response & res) {
  3115. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  3116. if (!params.embedding) {
  3117. res.status = 501;
  3118. res.set_content("This server does not support embeddings. Start it with `--embeddings`", "text/plain; charset=utf-8");
  3119. return;
  3120. }
  3121. const json body = json::parse(req.body);
  3122. bool is_openai = false;
  3123. // an input prompt can be a string or a list of tokens (integer)
  3124. json prompt;
  3125. if (body.count("input") != 0) {
  3126. is_openai = true;
  3127. prompt = body["input"];
  3128. } else if (body.count("content") != 0) {
  3129. // with "content", we only support single prompt
  3130. prompt = std::vector<std::string>{body["content"]};
  3131. } else {
  3132. res_error(res, format_error_response("\"input\" or \"content\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  3133. return;
  3134. }
  3135. // create and queue the task
  3136. json responses;
  3137. {
  3138. const int id_task = ctx_server.queue_tasks.get_new_id();
  3139. ctx_server.queue_results.add_waiting_task_id(id_task);
  3140. ctx_server.request_completion(id_task, -1, {{"prompt", prompt}}, false, true);
  3141. // get the result
  3142. server_task_result result = ctx_server.queue_results.recv(id_task);
  3143. ctx_server.queue_results.remove_waiting_task_id(id_task);
  3144. if (!result.error) {
  3145. if (result.data.count("results")) {
  3146. // result for multi-task
  3147. responses = result.data["results"];
  3148. } else {
  3149. // result for single task
  3150. responses = std::vector<json>{result.data};
  3151. }
  3152. } else {
  3153. // error received, ignore everything else
  3154. res_error(res, result.data);
  3155. return;
  3156. }
  3157. }
  3158. // write JSON response
  3159. json root = is_openai
  3160. ? format_embeddings_response_oaicompat(body, responses)
  3161. : responses[0];
  3162. return res.set_content(root.dump(), "application/json; charset=utf-8");
  3163. };
  3164. auto handle_static_file = [](unsigned char * content, size_t len, const char * mime_type) {
  3165. return [content, len, mime_type](const httplib::Request &, httplib::Response & res) {
  3166. res.set_content(reinterpret_cast<const char*>(content), len, mime_type);
  3167. return false;
  3168. };
  3169. };
  3170. //
  3171. // Router
  3172. //
  3173. // register static assets routes
  3174. if (!sparams.public_path.empty()) {
  3175. // Set the base directory for serving static files
  3176. svr->set_base_dir(sparams.public_path);
  3177. }
  3178. // using embedded static files
  3179. svr->Get("/", handle_static_file(index_html, index_html_len, "text/html; charset=utf-8"));
  3180. svr->Get("/index.js", handle_static_file(index_js, index_js_len, "text/javascript; charset=utf-8"));
  3181. svr->Get("/completion.js", handle_static_file(completion_js, completion_js_len, "text/javascript; charset=utf-8"));
  3182. svr->Get("/json-schema-to-grammar.mjs", handle_static_file(
  3183. json_schema_to_grammar_mjs, json_schema_to_grammar_mjs_len, "text/javascript; charset=utf-8"));
  3184. // register API routes
  3185. svr->Get ("/health", handle_health);
  3186. svr->Get ("/slots", handle_slots);
  3187. svr->Get ("/metrics", handle_metrics);
  3188. svr->Get ("/props", handle_props);
  3189. svr->Get ("/v1/models", handle_models);
  3190. svr->Post("/completion", handle_completions); // legacy
  3191. svr->Post("/completions", handle_completions);
  3192. svr->Post("/v1/completions", handle_completions);
  3193. svr->Post("/chat/completions", handle_chat_completions);
  3194. svr->Post("/v1/chat/completions", handle_chat_completions);
  3195. svr->Post("/infill", handle_infill);
  3196. svr->Post("/embedding", handle_embeddings); // legacy
  3197. svr->Post("/embeddings", handle_embeddings);
  3198. svr->Post("/v1/embeddings", handle_embeddings);
  3199. svr->Post("/tokenize", handle_tokenize);
  3200. svr->Post("/detokenize", handle_detokenize);
  3201. if (!sparams.slot_save_path.empty()) {
  3202. // only enable slot endpoints if slot_save_path is set
  3203. svr->Post("/slots/:id_slot", handle_slots_action);
  3204. }
  3205. //
  3206. // Start the server
  3207. //
  3208. if (sparams.n_threads_http < 1) {
  3209. // +2 threads for monitoring endpoints
  3210. sparams.n_threads_http = std::max(params.n_parallel + 2, (int32_t) std::thread::hardware_concurrency() - 1);
  3211. }
  3212. log_data["n_threads_http"] = std::to_string(sparams.n_threads_http);
  3213. svr->new_task_queue = [&sparams] { return new httplib::ThreadPool(sparams.n_threads_http); };
  3214. LOG_INFO("HTTP server listening", log_data);
  3215. // run the HTTP server in a thread - see comment below
  3216. std::thread t([&]() {
  3217. if (!svr->listen_after_bind()) {
  3218. state.store(SERVER_STATE_ERROR);
  3219. return 1;
  3220. }
  3221. return 0;
  3222. });
  3223. ctx_server.queue_tasks.on_new_task(std::bind(
  3224. &server_context::process_single_task, &ctx_server, std::placeholders::_1));
  3225. ctx_server.queue_tasks.on_finish_multitask(std::bind(
  3226. &server_context::on_finish_multitask, &ctx_server, std::placeholders::_1));
  3227. ctx_server.queue_tasks.on_update_slots(std::bind(
  3228. &server_context::update_slots, &ctx_server));
  3229. ctx_server.queue_results.on_multitask_update(std::bind(
  3230. &server_queue::update_multitask,
  3231. &ctx_server.queue_tasks,
  3232. std::placeholders::_1,
  3233. std::placeholders::_2,
  3234. std::placeholders::_3
  3235. ));
  3236. shutdown_handler = [&](int) {
  3237. ctx_server.queue_tasks.terminate();
  3238. };
  3239. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  3240. struct sigaction sigint_action;
  3241. sigint_action.sa_handler = signal_handler;
  3242. sigemptyset (&sigint_action.sa_mask);
  3243. sigint_action.sa_flags = 0;
  3244. sigaction(SIGINT, &sigint_action, NULL);
  3245. sigaction(SIGTERM, &sigint_action, NULL);
  3246. #elif defined (_WIN32)
  3247. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  3248. return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
  3249. };
  3250. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  3251. #endif
  3252. ctx_server.queue_tasks.start_loop();
  3253. svr->stop();
  3254. t.join();
  3255. llama_backend_free();
  3256. return 0;
  3257. }