server.cpp 154 KB

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