1
0

server.cpp 128 KB

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