1
0

server.cpp 142 KB

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