server.cpp 138 KB

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