1
0

server.cpp 135 KB

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