server.cpp 137 KB

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