server.cpp 137 KB

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