1
0

server.cpp 156 KB

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