server.cpp 136 KB

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