server.cpp 137 KB

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