server.cpp 131 KB

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