server.cpp 130 KB

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