server.cpp 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292
  1. // MIT License
  2. // Copyright (c) 2023 Georgi Gerganov
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. // The above copyright notice and this permission notice shall be included in all
  10. // copies or substantial portions of the Software.
  11. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. // SOFTWARE.
  18. #include "common.h"
  19. #include "llama.h"
  20. #include "grammar-parser.h"
  21. #include "utils.hpp"
  22. #include "../llava/clip.h"
  23. #include "../llava/llava.h"
  24. #include "stb_image.h"
  25. #ifndef NDEBUG
  26. // crash the server in debug mode, otherwise send an http 500 error
  27. #define CPPHTTPLIB_NO_EXCEPTIONS 1
  28. #endif
  29. // increase max payload length to allow use of larger context size
  30. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 1048576
  31. #include "httplib.h"
  32. #include "json.hpp"
  33. #include <cstddef>
  34. #include <thread>
  35. #include <chrono>
  36. #include <condition_variable>
  37. #include <atomic>
  38. #include <signal.h>
  39. using json = nlohmann::json;
  40. struct server_params {
  41. std::string hostname = "127.0.0.1";
  42. std::vector<std::string> api_keys;
  43. std::string public_path = "examples/server/public";
  44. std::string chat_template = "";
  45. int32_t port = 8080;
  46. int32_t read_timeout = 600;
  47. int32_t write_timeout = 600;
  48. bool slots_endpoint = true;
  49. bool metrics_endpoint = false;
  50. int n_threads_http = -1;
  51. };
  52. bool server_verbose = false;
  53. bool server_log_json = true;
  54. enum stop_type {
  55. STOP_FULL,
  56. STOP_PARTIAL,
  57. };
  58. // TODO: can become bool if we can't find use of more states
  59. enum slot_state {
  60. IDLE,
  61. PROCESSING,
  62. };
  63. enum slot_command {
  64. NONE,
  65. LOAD_PROMPT,
  66. RELEASE,
  67. };
  68. struct slot_params {
  69. bool stream = true;
  70. bool cache_prompt = false; // remember the prompt to avoid reprocessing all prompt
  71. uint32_t seed = -1; // RNG seed
  72. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  73. int32_t n_predict = -1; // new tokens to predict
  74. std::vector<std::string> antiprompt;
  75. json input_prefix;
  76. json input_suffix;
  77. };
  78. struct slot_image {
  79. int32_t id;
  80. bool request_encode_image = false;
  81. float * image_embedding = nullptr;
  82. int32_t image_tokens = 0;
  83. clip_image_u8 * img_data;
  84. std::string prefix_prompt; // before of this image
  85. };
  86. struct server_slot {
  87. int id;
  88. int task_id = -1;
  89. struct slot_params params;
  90. slot_state state = IDLE;
  91. slot_command command = NONE;
  92. // used to determine the slot that has been used the longest
  93. int64_t t_last_used = -1;
  94. // generation props
  95. int32_t n_ctx = 0; // context size per slot
  96. int32_t n_past = 0;
  97. int32_t n_decoded = 0;
  98. int32_t n_remaining = -1;
  99. int32_t i_batch = -1;
  100. int32_t n_predict = -1;
  101. int32_t n_prompt_tokens = 0;
  102. int32_t n_prompt_tokens_processed = 0;
  103. json prompt;
  104. std::string generated_text;
  105. llama_token sampled;
  106. std::vector<llama_token> cache_tokens;
  107. std::vector<completion_token_output> generated_token_probs;
  108. bool infill = false;
  109. bool embedding = false;
  110. bool has_next_token = true;
  111. bool truncated = false;
  112. bool stopped_eos = false;
  113. bool stopped_word = false;
  114. bool stopped_limit = false;
  115. std::string stopping_word;
  116. // sampling
  117. struct llama_sampling_params sparams;
  118. llama_sampling_context *ctx_sampling = nullptr;
  119. int32_t ga_i = 0; // group-attention state
  120. int32_t ga_n = 1; // group-attention factor
  121. int32_t ga_w = 512; // group-attention width
  122. int32_t n_past_se = 0; // self-extend
  123. // multimodal
  124. std::vector<slot_image> images;
  125. // stats
  126. size_t n_sent_text = 0; // number of sent text character
  127. size_t n_sent_token_probs = 0;
  128. int64_t t_start_process_prompt;
  129. int64_t t_start_genereration;
  130. double t_prompt_processing; // ms
  131. double t_token_generation; // ms
  132. // multitasks
  133. int multitask_id = -1;
  134. void reset() {
  135. n_prompt_tokens = 0;
  136. generated_text = "";
  137. truncated = false;
  138. stopped_eos = false;
  139. stopped_word = false;
  140. stopped_limit = false;
  141. stopping_word = "";
  142. n_past = 0;
  143. n_sent_text = 0;
  144. n_sent_token_probs = 0;
  145. infill = false;
  146. ga_i = 0;
  147. n_past_se = 0;
  148. generated_token_probs.clear();
  149. for (slot_image & img : images) {
  150. free(img.image_embedding);
  151. if (img.img_data) {
  152. clip_image_u8_free(img.img_data);
  153. }
  154. img.prefix_prompt = "";
  155. }
  156. images.clear();
  157. }
  158. bool has_budget(gpt_params &global_params) {
  159. if (params.n_predict == -1 && global_params.n_predict == -1) {
  160. return true; // limitless
  161. }
  162. n_remaining = -1;
  163. if (params.n_predict != -1) {
  164. n_remaining = params.n_predict - n_decoded;
  165. } else if (global_params.n_predict != -1) {
  166. n_remaining = global_params.n_predict - n_decoded;
  167. }
  168. return n_remaining > 0; // no budget
  169. }
  170. bool available() const {
  171. return state == IDLE && command == NONE;
  172. }
  173. bool is_processing() const {
  174. return (state == IDLE && command == LOAD_PROMPT) || state == PROCESSING;
  175. }
  176. void add_token_string(const completion_token_output &token) {
  177. if (command == RELEASE) {
  178. return;
  179. }
  180. cache_tokens.push_back(token.tok);
  181. generated_token_probs.push_back(token);
  182. }
  183. void release() {
  184. if (state == PROCESSING)
  185. {
  186. t_token_generation = (ggml_time_us() - t_start_genereration) / 1e3;
  187. command = RELEASE;
  188. }
  189. }
  190. json get_formated_timings() {
  191. return json
  192. {
  193. {"prompt_n", n_prompt_tokens_processed},
  194. {"prompt_ms", t_prompt_processing},
  195. {"prompt_per_token_ms", t_prompt_processing / n_prompt_tokens_processed},
  196. {"prompt_per_second", 1e3 / t_prompt_processing * n_prompt_tokens_processed},
  197. {"predicted_n", n_decoded},
  198. {"predicted_ms", t_token_generation},
  199. {"predicted_per_token_ms", t_token_generation / n_decoded},
  200. {"predicted_per_second", 1e3 / t_token_generation * n_decoded},
  201. };
  202. }
  203. void print_timings() const {
  204. char buffer[512];
  205. double t_token = t_prompt_processing / n_prompt_tokens_processed;
  206. double n_tokens_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  207. sprintf(buffer, "prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)",
  208. t_prompt_processing, n_prompt_tokens_processed,
  209. t_token, n_tokens_second);
  210. LOG_INFO(buffer, {
  211. {"slot_id", id},
  212. {"task_id", task_id},
  213. {"t_prompt_processing", t_prompt_processing},
  214. {"n_prompt_tokens_processed", n_prompt_tokens_processed},
  215. {"t_token", t_token},
  216. {"n_tokens_second", n_tokens_second},
  217. });
  218. t_token = t_token_generation / n_decoded;
  219. n_tokens_second = 1e3 / t_token_generation * n_decoded;
  220. sprintf(buffer, "generation eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)",
  221. t_token_generation, n_decoded,
  222. t_token, n_tokens_second);
  223. LOG_INFO(buffer, {
  224. {"slot_id", id},
  225. {"task_id", task_id},
  226. {"t_token_generation", t_token_generation},
  227. {"n_decoded", n_decoded},
  228. {"t_token", t_token},
  229. {"n_tokens_second", n_tokens_second},
  230. });
  231. sprintf(buffer, " total time = %10.2f ms", t_prompt_processing + t_token_generation);
  232. LOG_INFO(buffer, {
  233. {"slot_id", id},
  234. {"task_id", task_id},
  235. {"t_prompt_processing", t_prompt_processing},
  236. {"t_token_generation", t_token_generation},
  237. {"t_total", t_prompt_processing + t_token_generation},
  238. });
  239. }
  240. };
  241. struct server_metrics {
  242. uint64_t n_prompt_tokens_processed_total = 0;
  243. uint64_t n_tokens_predicted_total = 0;
  244. uint64_t n_prompt_tokens_processed = 0;
  245. uint64_t t_prompt_processing = 0;
  246. uint64_t n_tokens_predicted = 0;
  247. uint64_t t_tokens_generation = 0;
  248. void on_prompt_eval(const server_slot &slot) {
  249. n_prompt_tokens_processed_total += slot.n_prompt_tokens_processed;
  250. n_prompt_tokens_processed += slot.n_prompt_tokens_processed;
  251. t_prompt_processing += slot.t_prompt_processing;
  252. }
  253. void on_prediction(const server_slot &slot) {
  254. n_tokens_predicted_total += slot.n_decoded;
  255. n_tokens_predicted += slot.n_decoded;
  256. t_tokens_generation += slot.t_token_generation;
  257. }
  258. void reset_bucket() {
  259. n_prompt_tokens_processed = 0;
  260. t_prompt_processing = 0;
  261. n_tokens_predicted = 0;
  262. t_tokens_generation = 0;
  263. }
  264. };
  265. struct llama_server_context
  266. {
  267. llama_model *model = nullptr;
  268. llama_context *ctx = nullptr;
  269. clip_ctx *clp_ctx = nullptr;
  270. gpt_params params;
  271. llama_batch batch;
  272. bool multimodal = false;
  273. bool clean_kv_cache = true;
  274. bool all_slots_are_idle = false;
  275. bool add_bos_token = true;
  276. int32_t n_ctx; // total context for all clients / slots
  277. // system prompt
  278. bool system_need_update = false;
  279. std::string system_prompt;
  280. std::vector<llama_token> system_tokens;
  281. std::string name_user; // this should be the antiprompt
  282. std::string name_assistant;
  283. // slots / clients
  284. std::vector<server_slot> slots;
  285. json default_generation_settings_for_props;
  286. llama_server_queue queue_tasks;
  287. llama_server_response queue_results;
  288. server_metrics metrics;
  289. ~llama_server_context()
  290. {
  291. if (clp_ctx)
  292. {
  293. LOG_INFO("freeing clip model", {});
  294. clip_free(clp_ctx);
  295. clp_ctx = nullptr;
  296. }
  297. if (ctx)
  298. {
  299. llama_free(ctx);
  300. ctx = nullptr;
  301. }
  302. if (model)
  303. {
  304. llama_free_model(model);
  305. model = nullptr;
  306. }
  307. }
  308. bool load_model(const gpt_params &params_)
  309. {
  310. params = params_;
  311. if (!params.mmproj.empty()) {
  312. multimodal = true;
  313. LOG_INFO("Multi Modal Mode Enabled", {});
  314. clp_ctx = clip_model_load(params.mmproj.c_str(), /*verbosity=*/ 1);
  315. if(clp_ctx == nullptr) {
  316. LOG_ERROR("unable to load clip model", {{"model", params.mmproj}});
  317. return false;
  318. }
  319. if (params.n_ctx < 2048) { // request larger context for the image embedding
  320. params.n_ctx = 2048;
  321. }
  322. }
  323. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  324. if (model == nullptr)
  325. {
  326. LOG_ERROR("unable to load model", {{"model", params.model}});
  327. return false;
  328. }
  329. if (multimodal) {
  330. const int n_embd_clip = clip_n_mmproj_embd(clp_ctx);
  331. const int n_embd_llm = llama_n_embd(model);
  332. if (n_embd_clip != n_embd_llm) {
  333. LOG_TEE("%s: embedding dim of the multimodal projector (%d) is not equal to that of LLaMA (%d). Make sure that you use the correct mmproj file.\n", __func__, n_embd_clip, n_embd_llm);
  334. llama_free(ctx);
  335. llama_free_model(model);
  336. return false;
  337. }
  338. }
  339. n_ctx = llama_n_ctx(ctx);
  340. add_bos_token = llama_should_add_bos_token(model);
  341. return true;
  342. }
  343. void validate_model_chat_template(server_params & sparams) {
  344. llama_chat_message chat[] = {{"user", "test"}};
  345. std::vector<char> buf(1);
  346. int res = llama_chat_apply_template(model, nullptr, chat, 1, true, buf.data(), buf.size());
  347. if (res < 0) {
  348. LOG_ERROR("The chat template comes with this model is not yet supported, falling back to chatml. This may cause the model to output suboptimal responses", {});
  349. sparams.chat_template = "chatml";
  350. }
  351. }
  352. void initialize() {
  353. // create slots
  354. all_slots_are_idle = true;
  355. const int32_t n_ctx_slot = n_ctx / params.n_parallel;
  356. LOG_INFO("initializing slots", {{"n_slots", params.n_parallel}});
  357. for (int i = 0; i < params.n_parallel; i++)
  358. {
  359. server_slot slot;
  360. slot.id = i;
  361. slot.n_ctx = n_ctx_slot;
  362. slot.n_predict = params.n_predict;
  363. LOG_INFO("new slot", {
  364. {"slot_id", slot.id},
  365. {"n_ctx_slot", slot.n_ctx}
  366. });
  367. const int ga_n = params.grp_attn_n;
  368. const int ga_w = params.grp_attn_w;
  369. if (ga_n != 1) {
  370. GGML_ASSERT(ga_n > 0 && "ga_n must be positive"); // NOLINT
  371. GGML_ASSERT(ga_w % ga_n == 0 && "ga_w must be a multiple of ga_n"); // NOLINT
  372. //GGML_ASSERT(n_ctx_train % ga_w == 0 && "n_ctx_train must be a multiple of ga_w"); // NOLINT
  373. //GGML_ASSERT(n_ctx >= n_ctx_train * ga_n && "n_ctx must be at least n_ctx_train * ga_n"); // NOLINT
  374. LOG_INFO("slot self-extend", {
  375. {"slot_id", slot.id},
  376. {"ga_n", ga_n},
  377. {"ga_w", ga_w}
  378. });
  379. }
  380. slot.ga_i = 0;
  381. slot.ga_n = ga_n;
  382. slot.ga_w = ga_w;
  383. slot.reset();
  384. slots.push_back(slot);
  385. }
  386. default_generation_settings_for_props = get_formated_generation(slots.front());
  387. default_generation_settings_for_props["seed"] = -1;
  388. batch = llama_batch_init(n_ctx, 0, params.n_parallel);
  389. }
  390. std::vector<llama_token> tokenize(const json & json_prompt, bool add_bos) const
  391. {
  392. // TODO: currently, we tokenize using special tokens by default
  393. // this is not always correct (see https://github.com/ggerganov/llama.cpp/pull/4160#issuecomment-1824826216)
  394. // but it's better compared to completely ignoring ChatML and other chat templates
  395. const bool TMP_FORCE_SPECIAL = true;
  396. // If `add_bos` is true, we only add BOS, when json_prompt is a string,
  397. // or the first element of the json_prompt array is a string.
  398. std::vector<llama_token> prompt_tokens;
  399. if (json_prompt.is_array())
  400. {
  401. bool first = true;
  402. for (const auto& p : json_prompt)
  403. {
  404. if (p.is_string())
  405. {
  406. auto s = p.template get<std::string>();
  407. std::vector<llama_token> p;
  408. if (first)
  409. {
  410. p = ::llama_tokenize(ctx, s, add_bos, TMP_FORCE_SPECIAL);
  411. first = false;
  412. }
  413. else
  414. {
  415. p = ::llama_tokenize(ctx, s, false, TMP_FORCE_SPECIAL);
  416. }
  417. prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
  418. }
  419. else
  420. {
  421. if (first)
  422. {
  423. first = false;
  424. }
  425. prompt_tokens.push_back(p.template get<llama_token>());
  426. }
  427. }
  428. }
  429. else
  430. {
  431. auto s = json_prompt.template get<std::string>();
  432. prompt_tokens = ::llama_tokenize(ctx, s, add_bos, TMP_FORCE_SPECIAL);
  433. }
  434. return prompt_tokens;
  435. }
  436. server_slot* get_slot(int id) {
  437. int64_t t_last = ggml_time_us();
  438. server_slot *last_used = nullptr;
  439. for (server_slot & slot : slots)
  440. {
  441. if (slot.id == id && slot.available())
  442. {
  443. return &slot;
  444. }
  445. if (slot.available() && slot.t_last_used < t_last)
  446. {
  447. last_used = &slot;
  448. t_last = slot.t_last_used;
  449. }
  450. }
  451. return last_used;
  452. }
  453. bool launch_slot_with_data(server_slot* &slot, json data) {
  454. slot_params default_params;
  455. llama_sampling_params default_sparams;
  456. slot->params.stream = json_value(data, "stream", false);
  457. slot->params.cache_prompt = json_value(data, "cache_prompt", false);
  458. slot->params.n_predict = json_value(data, "n_predict", default_params.n_predict);
  459. slot->sparams.top_k = json_value(data, "top_k", default_sparams.top_k);
  460. slot->sparams.top_p = json_value(data, "top_p", default_sparams.top_p);
  461. slot->sparams.min_p = json_value(data, "min_p", default_sparams.min_p);
  462. slot->sparams.tfs_z = json_value(data, "tfs_z", default_sparams.tfs_z);
  463. slot->sparams.typical_p = json_value(data, "typical_p", default_sparams.typical_p);
  464. slot->sparams.temp = json_value(data, "temperature", default_sparams.temp);
  465. slot->sparams.dynatemp_range = json_value(data, "dynatemp_range", default_sparams.dynatemp_range);
  466. slot->sparams.dynatemp_exponent = json_value(data, "dynatemp_exponent", default_sparams.dynatemp_exponent);
  467. slot->sparams.penalty_last_n = json_value(data, "repeat_last_n", default_sparams.penalty_last_n);
  468. slot->sparams.penalty_repeat = json_value(data, "repeat_penalty", default_sparams.penalty_repeat);
  469. slot->sparams.penalty_freq = json_value(data, "frequency_penalty", default_sparams.penalty_freq);
  470. slot->sparams.penalty_present = json_value(data, "presence_penalty", default_sparams.penalty_present);
  471. slot->sparams.mirostat = json_value(data, "mirostat", default_sparams.mirostat);
  472. slot->sparams.mirostat_tau = json_value(data, "mirostat_tau", default_sparams.mirostat_tau);
  473. slot->sparams.mirostat_eta = json_value(data, "mirostat_eta", default_sparams.mirostat_eta);
  474. slot->sparams.penalize_nl = json_value(data, "penalize_nl", default_sparams.penalize_nl);
  475. slot->params.n_keep = json_value(data, "n_keep", slot->params.n_keep);
  476. slot->params.seed = json_value(data, "seed", default_params.seed);
  477. slot->sparams.grammar = json_value(data, "grammar", default_sparams.grammar);
  478. slot->sparams.n_probs = json_value(data, "n_probs", default_sparams.n_probs);
  479. slot->sparams.min_keep = json_value(data, "min_keep", default_sparams.min_keep);
  480. if (slot->n_predict > 0 && slot->params.n_predict > slot->n_predict) {
  481. // Might be better to reject the request with a 400 ?
  482. LOG_WARNING("Max tokens to predict exceeds server configuration", {
  483. {"params.n_predict", slot->params.n_predict},
  484. {"slot.n_predict", slot->n_predict},
  485. });
  486. slot->params.n_predict = slot->n_predict;
  487. }
  488. // infill
  489. if (data.count("input_prefix") != 0)
  490. {
  491. slot->params.input_prefix = data["input_prefix"];
  492. }
  493. else
  494. {
  495. slot->params.input_prefix = "";
  496. }
  497. if (data.count("input_suffix") != 0)
  498. {
  499. slot->params.input_suffix = data["input_suffix"];
  500. }
  501. else
  502. {
  503. slot->params.input_suffix = "";
  504. }
  505. if (data.count("prompt") != 0)
  506. {
  507. slot->prompt = data["prompt"];
  508. }
  509. else
  510. {
  511. slot->prompt = "";
  512. }
  513. slot->sparams.penalty_prompt_tokens.clear();
  514. slot->sparams.use_penalty_prompt_tokens = false;
  515. const auto &penalty_prompt = data.find("penalty_prompt");
  516. if (penalty_prompt != data.end())
  517. {
  518. if (penalty_prompt->is_string())
  519. {
  520. const auto penalty_prompt_string = penalty_prompt->get<std::string>();
  521. auto penalty_tokens = llama_tokenize(model, penalty_prompt_string, false);
  522. slot->sparams.penalty_prompt_tokens.swap(penalty_tokens);
  523. if (slot->params.n_predict > 0)
  524. {
  525. slot->sparams.penalty_prompt_tokens.reserve(slot->sparams.penalty_prompt_tokens.size() + slot->params.n_predict);
  526. }
  527. slot->sparams.use_penalty_prompt_tokens = true;
  528. }
  529. else if (penalty_prompt->is_array())
  530. {
  531. const auto n_tokens = penalty_prompt->size();
  532. slot->sparams.penalty_prompt_tokens.reserve(n_tokens + std::max(0, slot->params.n_predict));
  533. const int n_vocab = llama_n_vocab(model);
  534. for (const auto &penalty_token : *penalty_prompt)
  535. {
  536. if (penalty_token.is_number_integer())
  537. {
  538. const auto tok = penalty_token.get<llama_token>();
  539. if (tok >= 0 && tok < n_vocab)
  540. {
  541. slot->sparams.penalty_prompt_tokens.push_back(tok);
  542. }
  543. }
  544. }
  545. slot->sparams.use_penalty_prompt_tokens = true;
  546. }
  547. }
  548. slot->sparams.logit_bias.clear();
  549. if (json_value(data, "ignore_eos", false))
  550. {
  551. slot->sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  552. }
  553. const auto &logit_bias = data.find("logit_bias");
  554. if (logit_bias != data.end() && logit_bias->is_array())
  555. {
  556. const int n_vocab = llama_n_vocab(model);
  557. for (const auto &el : *logit_bias)
  558. {
  559. if (el.is_array() && el.size() == 2)
  560. {
  561. float bias;
  562. if (el[1].is_number())
  563. {
  564. bias = el[1].get<float>();
  565. }
  566. else if (el[1].is_boolean() && !el[1].get<bool>())
  567. {
  568. bias = -INFINITY;
  569. }
  570. else
  571. {
  572. continue;
  573. }
  574. if (el[0].is_number_integer())
  575. {
  576. llama_token tok = el[0].get<llama_token>();
  577. if (tok >= 0 && tok < n_vocab)
  578. {
  579. slot->sparams.logit_bias[tok] = bias;
  580. }
  581. }
  582. else if (el[0].is_string())
  583. {
  584. auto toks = llama_tokenize(model, el[0].get<std::string>(), false);
  585. for (auto tok : toks)
  586. {
  587. slot->sparams.logit_bias[tok] = bias;
  588. }
  589. }
  590. }
  591. }
  592. }
  593. slot->params.antiprompt.clear();
  594. const auto &stop = data.find("stop");
  595. if (stop != data.end() && stop->is_array())
  596. {
  597. for (const auto &word : *stop)
  598. {
  599. if (!word.empty())
  600. {
  601. slot->params.antiprompt.push_back(word);
  602. }
  603. }
  604. }
  605. const auto &samplers_sequence = data.find("samplers");
  606. if (samplers_sequence != data.end() && samplers_sequence->is_array())
  607. {
  608. std::vector<std::string> sampler_names;
  609. for (const auto &sampler_name : *samplers_sequence)
  610. {
  611. if (sampler_name.is_string())
  612. {
  613. sampler_names.emplace_back(sampler_name);
  614. }
  615. }
  616. slot->sparams.samplers_sequence = sampler_types_from_names(sampler_names, false);
  617. }
  618. else
  619. {
  620. slot->sparams.samplers_sequence = default_sparams.samplers_sequence;
  621. }
  622. if (multimodal)
  623. {
  624. const auto &images_data = data.find("image_data");
  625. if (images_data != data.end() && images_data->is_array())
  626. {
  627. for (const auto &img : *images_data)
  628. {
  629. const std::vector<uint8_t> image_buffer = base64_decode(img["data"].get<std::string>());
  630. slot_image img_sl;
  631. img_sl.id = img.count("id") != 0 ? img["id"].get<int>() : slot->images.size();
  632. img_sl.img_data = clip_image_u8_init();
  633. if (!clip_image_load_from_bytes(image_buffer.data(), image_buffer.size(), img_sl.img_data))
  634. {
  635. LOG_ERROR("failed to load image", {
  636. {"slot_id", slot->id},
  637. {"img_sl_id", img_sl.id}
  638. });
  639. return false;
  640. }
  641. LOG_VERBOSE("image loaded", {
  642. {"slot_id", slot->id},
  643. {"img_sl_id", img_sl.id}
  644. });
  645. img_sl.request_encode_image = true;
  646. slot->images.push_back(img_sl);
  647. }
  648. // process prompt
  649. // example: system prompt [img-102] user [img-103] describe [img-134] -> [{id: 102, prefix: 'system prompt '}, {id: 103, prefix: ' user '}, {id: 134, prefix: ' describe '}]}
  650. if (slot->images.size() > 0 && !slot->prompt.is_array())
  651. {
  652. std::string prompt = slot->prompt.get<std::string>();
  653. size_t pos = 0, begin_prefix = 0;
  654. std::string pattern = "[img-";
  655. while ((pos = prompt.find(pattern, pos)) != std::string::npos) {
  656. size_t end_prefix = pos;
  657. pos += pattern.length();
  658. size_t end_pos = prompt.find(']', pos);
  659. if (end_pos != std::string::npos)
  660. {
  661. std::string image_id = prompt.substr(pos, end_pos - pos);
  662. try
  663. {
  664. int img_id = std::stoi(image_id);
  665. bool found = false;
  666. for (slot_image &img : slot->images)
  667. {
  668. if (img.id == img_id) {
  669. found = true;
  670. img.prefix_prompt = prompt.substr(begin_prefix, end_prefix - begin_prefix);
  671. begin_prefix = end_pos + 1;
  672. break;
  673. }
  674. }
  675. if (!found) {
  676. LOG_TEE("ERROR: Image with id: %i, not found.\n", img_id);
  677. slot->images.clear();
  678. return false;
  679. }
  680. } catch (const std::invalid_argument& e) {
  681. LOG_TEE("Invalid image number id in prompt\n");
  682. slot->images.clear();
  683. return false;
  684. }
  685. }
  686. }
  687. slot->prompt = "";
  688. slot->params.input_suffix = prompt.substr(begin_prefix);
  689. slot->params.cache_prompt = false; // multimodal doesn't support cache prompt
  690. }
  691. }
  692. }
  693. if (slot->ctx_sampling != nullptr)
  694. {
  695. llama_sampling_free(slot->ctx_sampling);
  696. }
  697. slot->ctx_sampling = llama_sampling_init(slot->sparams);
  698. llama_set_rng_seed(ctx, slot->params.seed);
  699. slot->command = LOAD_PROMPT;
  700. all_slots_are_idle = false;
  701. LOG_INFO("slot is processing task", {
  702. {"slot_id", slot->id},
  703. {"task_id", slot->task_id},
  704. });
  705. return true;
  706. }
  707. void kv_cache_clear() {
  708. // clear the entire KV cache
  709. llama_kv_cache_clear(ctx);
  710. clean_kv_cache = false;
  711. }
  712. void system_prompt_update() {
  713. kv_cache_clear();
  714. system_tokens.clear();
  715. if (!system_prompt.empty()) {
  716. system_tokens = ::llama_tokenize(ctx, system_prompt, add_bos_token);
  717. llama_batch_clear(batch);
  718. for (int i = 0; i < (int)system_tokens.size(); ++i)
  719. {
  720. llama_batch_add(batch, system_tokens[i], i, { 0 }, false);
  721. }
  722. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += params.n_batch)
  723. {
  724. const int32_t n_tokens = std::min(params.n_batch, (int32_t) (batch.n_tokens - i));
  725. llama_batch batch_view = {
  726. n_tokens,
  727. batch.token + i,
  728. nullptr,
  729. batch.pos + i,
  730. batch.n_seq_id + i,
  731. batch.seq_id + i,
  732. batch.logits + i,
  733. 0, 0, 0, // unused
  734. };
  735. if (llama_decode(ctx, batch_view) != 0)
  736. {
  737. LOG_TEE("%s: llama_decode() failed\n", __func__);
  738. return;
  739. }
  740. }
  741. // assign the system KV cache to all parallel sequences
  742. for (int32_t i = 1; i < params.n_parallel; ++i)
  743. {
  744. llama_kv_cache_seq_cp(ctx, 0, i, 0, system_tokens.size());
  745. }
  746. }
  747. LOG_TEE("system prompt updated\n");
  748. system_need_update = false;
  749. }
  750. void system_prompt_notify() {
  751. // release all slots
  752. for (server_slot &slot : slots)
  753. {
  754. slot.release();
  755. }
  756. system_need_update = true;
  757. }
  758. void system_prompt_process(const json &sys_props) {
  759. system_prompt = sys_props.value("prompt", "");
  760. name_user = sys_props.value("anti_prompt", "");
  761. name_assistant = sys_props.value("assistant_name", "");
  762. system_prompt_notify();
  763. }
  764. static size_t find_stopping_strings(const std::string &text, const size_t last_token_size,
  765. const stop_type type, server_slot &slot)
  766. {
  767. size_t stop_pos = std::string::npos;
  768. for (const std::string &word : slot.params.antiprompt)
  769. {
  770. size_t pos;
  771. if (type == STOP_FULL)
  772. {
  773. const size_t tmp = word.size() + last_token_size;
  774. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  775. pos = text.find(word, from_pos);
  776. }
  777. else
  778. {
  779. pos = find_partial_stop_string(word, text);
  780. }
  781. if (pos != std::string::npos &&
  782. (stop_pos == std::string::npos || pos < stop_pos))
  783. {
  784. if (type == STOP_FULL)
  785. {
  786. slot.stopped_word = true;
  787. slot.stopping_word = word;
  788. slot.has_next_token = false;
  789. }
  790. stop_pos = pos;
  791. }
  792. }
  793. return stop_pos;
  794. }
  795. bool process_token(completion_token_output &result, server_slot &slot) {
  796. // remember which tokens were sampled - used for repetition penalties during sampling
  797. const std::string token_str = llama_token_to_piece(ctx, result.tok);
  798. slot.sampled = result.tok;
  799. // search stop word and delete it
  800. slot.generated_text += token_str;
  801. slot.has_next_token = true;
  802. if (slot.ctx_sampling->params.use_penalty_prompt_tokens && result.tok != -1)
  803. {
  804. // we can change penalty_prompt_tokens because it is always created from scratch each request
  805. slot.ctx_sampling->params.penalty_prompt_tokens.push_back(result.tok);
  806. }
  807. // check if there is incomplete UTF-8 character at the end
  808. bool incomplete = false;
  809. for (unsigned i = 1; i < 5 && i <= slot.generated_text.size(); ++i)
  810. {
  811. unsigned char c = slot.generated_text[slot.generated_text.size() - i];
  812. if ((c & 0xC0) == 0x80)
  813. {
  814. // continuation byte: 10xxxxxx
  815. continue;
  816. }
  817. if ((c & 0xE0) == 0xC0)
  818. {
  819. // 2-byte character: 110xxxxx ...
  820. incomplete = i < 2;
  821. }
  822. else if ((c & 0xF0) == 0xE0)
  823. {
  824. // 3-byte character: 1110xxxx ...
  825. incomplete = i < 3;
  826. }
  827. else if ((c & 0xF8) == 0xF0)
  828. {
  829. // 4-byte character: 11110xxx ...
  830. incomplete = i < 4;
  831. }
  832. // else 1-byte character or invalid byte
  833. break;
  834. }
  835. if (!incomplete)
  836. {
  837. size_t pos = std::min(slot.n_sent_text, slot.generated_text.size());
  838. const std::string str_test = slot.generated_text.substr(pos);
  839. bool is_stop_full = false;
  840. size_t stop_pos = find_stopping_strings(str_test, token_str.size(), STOP_FULL, slot);
  841. if (stop_pos != std::string::npos)
  842. {
  843. is_stop_full = true;
  844. slot.generated_text.erase(
  845. slot.generated_text.begin() + pos + stop_pos,
  846. slot.generated_text.end());
  847. pos = std::min(slot.n_sent_text, slot.generated_text.size());
  848. }
  849. else
  850. {
  851. is_stop_full = false;
  852. stop_pos = find_stopping_strings(str_test, token_str.size(), STOP_PARTIAL, slot);
  853. }
  854. // check if there is any token to predict
  855. if (stop_pos == std::string::npos || (!slot.has_next_token && !is_stop_full && stop_pos > 0))
  856. {
  857. // no send the stop word in the response
  858. result.text_to_send = slot.generated_text.substr(pos, std::string::npos);
  859. slot.n_sent_text += result.text_to_send.size();
  860. // add the token to slot queue and cache
  861. }
  862. if (slot.params.stream)
  863. {
  864. send_partial_response(slot, result);
  865. }
  866. }
  867. slot.add_token_string(result);
  868. if (incomplete)
  869. {
  870. slot.has_next_token = true;
  871. }
  872. // check the limits
  873. if (slot.n_decoded > 0 && slot.has_next_token && !slot.has_budget(params))
  874. {
  875. slot.stopped_limit = true;
  876. slot.has_next_token = false;
  877. }
  878. if (!slot.cache_tokens.empty() && result.tok == llama_token_eos(model))
  879. {
  880. slot.stopped_eos = true;
  881. slot.has_next_token = false;
  882. LOG_VERBOSE("eos token found", {});
  883. }
  884. LOG_VERBOSE("next token", {
  885. {"token", result.tok},
  886. {"token_text", tokens_to_output_formatted_string(ctx, result.tok)},
  887. {"has_next_token", slot.has_next_token},
  888. {"n_remain", slot.n_remaining},
  889. {"num_tokens_predicted", slot.n_decoded},
  890. {"stopped_eos", slot.stopped_eos},
  891. {"stopped_word", slot.stopped_word},
  892. {"stopped_limit", slot.stopped_limit},
  893. {"stopping_word", slot.stopping_word},
  894. });
  895. return slot.has_next_token; // continue
  896. }
  897. bool process_images(server_slot &slot) const
  898. {
  899. for (slot_image &img : slot.images)
  900. {
  901. if (!img.request_encode_image)
  902. {
  903. continue;
  904. }
  905. if (!llava_image_embed_make_with_clip_img(clp_ctx, params.n_threads, img.img_data, &img.image_embedding, &img.image_tokens)) {
  906. LOG_TEE("Error processing the given image");
  907. return false;
  908. }
  909. img.request_encode_image = false;
  910. }
  911. return slot.images.size() > 0;
  912. }
  913. void send_error(task_server& task, const std::string &error)
  914. {
  915. LOG_TEE("task %i - error: %s\n", task.id, error.c_str());
  916. task_result res;
  917. res.id = task.id;
  918. res.multitask_id = task.multitask_id;
  919. res.stop = false;
  920. res.error = true;
  921. res.result_json = { { "content", error } };
  922. queue_results.send(res);
  923. }
  924. json get_formated_generation(server_slot &slot)
  925. {
  926. const auto eos_bias = slot.sparams.logit_bias.find(llama_token_eos(model));
  927. const bool ignore_eos = eos_bias != slot.sparams.logit_bias.end() &&
  928. eos_bias->second < 0.0f && std::isinf(eos_bias->second);
  929. std::vector<std::string> samplers_sequence;
  930. for (const auto &sampler_type : slot.sparams.samplers_sequence)
  931. {
  932. samplers_sequence.emplace_back(sampler_type_to_name_string(sampler_type));
  933. }
  934. return json {
  935. {"n_ctx", slot.n_ctx},
  936. {"n_predict", slot.n_predict},
  937. {"model", params.model_alias},
  938. {"seed", slot.params.seed},
  939. {"temperature", slot.sparams.temp},
  940. {"dynatemp_range", slot.sparams.dynatemp_range},
  941. {"dynatemp_exponent", slot.sparams.dynatemp_exponent},
  942. {"top_k", slot.sparams.top_k},
  943. {"top_p", slot.sparams.top_p},
  944. {"min_p", slot.sparams.min_p},
  945. {"tfs_z", slot.sparams.tfs_z},
  946. {"typical_p", slot.sparams.typical_p},
  947. {"repeat_last_n", slot.sparams.penalty_last_n},
  948. {"repeat_penalty", slot.sparams.penalty_repeat},
  949. {"presence_penalty", slot.sparams.penalty_present},
  950. {"frequency_penalty", slot.sparams.penalty_freq},
  951. {"penalty_prompt_tokens", slot.sparams.penalty_prompt_tokens},
  952. {"use_penalty_prompt_tokens", slot.sparams.use_penalty_prompt_tokens},
  953. {"mirostat", slot.sparams.mirostat},
  954. {"mirostat_tau", slot.sparams.mirostat_tau},
  955. {"mirostat_eta", slot.sparams.mirostat_eta},
  956. {"penalize_nl", slot.sparams.penalize_nl},
  957. {"stop", slot.params.antiprompt},
  958. {"n_predict", slot.params.n_predict},
  959. {"n_keep", params.n_keep},
  960. {"ignore_eos", ignore_eos},
  961. {"stream", slot.params.stream},
  962. {"logit_bias", slot.sparams.logit_bias},
  963. {"n_probs", slot.sparams.n_probs},
  964. {"min_keep", slot.sparams.min_keep},
  965. {"grammar", slot.sparams.grammar},
  966. {"samplers", samplers_sequence}
  967. };
  968. }
  969. void send_partial_response(server_slot &slot, completion_token_output tkn)
  970. {
  971. task_result res;
  972. res.id = slot.task_id;
  973. res.multitask_id = slot.multitask_id;
  974. res.error = false;
  975. res.stop = false;
  976. res.result_json = json
  977. {
  978. {"content", tkn.text_to_send},
  979. {"stop", false},
  980. {"slot_id", slot.id},
  981. {"multimodal", multimodal}
  982. };
  983. if (slot.sparams.n_probs > 0)
  984. {
  985. std::vector<completion_token_output> probs_output = {};
  986. const std::vector<llama_token> to_send_toks = llama_tokenize(ctx, tkn.text_to_send, false);
  987. size_t probs_pos = std::min(slot.n_sent_token_probs, slot.generated_token_probs.size());
  988. size_t probs_stop_pos = std::min(slot.n_sent_token_probs + to_send_toks.size(), slot.generated_token_probs.size());
  989. if (probs_pos < probs_stop_pos)
  990. {
  991. probs_output = std::vector<completion_token_output>(slot.generated_token_probs.begin() + probs_pos, slot.generated_token_probs.begin() + probs_stop_pos);
  992. }
  993. slot.n_sent_token_probs = probs_stop_pos;
  994. res.result_json["completion_probabilities"] = probs_vector_to_json(ctx, probs_output);
  995. }
  996. queue_results.send(res);
  997. }
  998. void send_final_response(server_slot &slot)
  999. {
  1000. task_result res;
  1001. res.id = slot.task_id;
  1002. res.multitask_id = slot.multitask_id;
  1003. res.error = false;
  1004. res.stop = true;
  1005. res.result_json = json
  1006. {
  1007. {"content", !slot.params.stream ? slot.generated_text : ""},
  1008. {"slot_id", slot.id},
  1009. {"stop", true},
  1010. {"model", params.model_alias},
  1011. {"tokens_predicted", slot.n_decoded},
  1012. {"tokens_evaluated", slot.n_prompt_tokens},
  1013. {"generation_settings", get_formated_generation(slot)},
  1014. {"prompt", slot.prompt},
  1015. {"truncated", slot.truncated},
  1016. {"stopped_eos", slot.stopped_eos},
  1017. {"stopped_word", slot.stopped_word},
  1018. {"stopped_limit", slot.stopped_limit},
  1019. {"stopping_word", slot.stopping_word},
  1020. {"tokens_cached", slot.n_past},
  1021. {"timings", slot.get_formated_timings()}
  1022. };
  1023. if (slot.sparams.n_probs > 0)
  1024. {
  1025. std::vector<completion_token_output> probs = {};
  1026. if (!slot.params.stream && slot.stopped_word)
  1027. {
  1028. const std::vector<llama_token> stop_word_toks = llama_tokenize(ctx, slot.stopping_word, false);
  1029. probs = std::vector<completion_token_output>(slot.generated_token_probs.begin(), slot.generated_token_probs.end() - stop_word_toks.size());
  1030. }
  1031. else
  1032. {
  1033. probs = std::vector<completion_token_output>(
  1034. slot.generated_token_probs.begin(),
  1035. slot.generated_token_probs.end());
  1036. }
  1037. res.result_json["completion_probabilities"] = probs_vector_to_json(ctx, probs);
  1038. }
  1039. queue_results.send(res);
  1040. }
  1041. void send_embedding(server_slot & slot, const llama_batch & batch)
  1042. {
  1043. task_result res;
  1044. res.id = slot.task_id;
  1045. res.multitask_id = slot.multitask_id;
  1046. res.error = false;
  1047. res.stop = true;
  1048. const int n_embd = llama_n_embd(model);
  1049. if (!params.embedding)
  1050. {
  1051. LOG_WARNING("embedding disabled", {{"params.embedding", params.embedding}});
  1052. res.result_json = json
  1053. {
  1054. {"embedding", std::vector<float>(n_embd, 0.0f)},
  1055. };
  1056. }
  1057. else
  1058. {
  1059. for (int i = 0; i < batch.n_tokens; ++i) {
  1060. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  1061. continue;
  1062. }
  1063. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1064. if (embd == NULL) {
  1065. embd = llama_get_embeddings_ith(ctx, i);
  1066. if (embd == NULL) {
  1067. LOG_ERROR("failed to get embeddings for token", {{"token", batch.token[i]}, {"seq_id", batch.seq_id[i][0]}});
  1068. res.result_json = json
  1069. {
  1070. {"embedding", std::vector<float>(n_embd, 0.0f)},
  1071. };
  1072. continue;
  1073. }
  1074. }
  1075. res.result_json = json
  1076. {
  1077. {"embedding", std::vector<float>(embd, embd + n_embd)},
  1078. };
  1079. }
  1080. }
  1081. queue_results.send(res);
  1082. }
  1083. void request_completion(int task_id, json data, bool infill, bool embedding, int multitask_id)
  1084. {
  1085. task_server task;
  1086. task.id = task_id;
  1087. task.target_id = 0;
  1088. task.data = std::move(data);
  1089. task.infill_mode = infill;
  1090. task.embedding_mode = embedding;
  1091. task.type = TASK_TYPE_COMPLETION;
  1092. task.multitask_id = multitask_id;
  1093. // when a completion task's prompt array is not a singleton, we split it into multiple requests
  1094. // otherwise, it's a single-prompt task, we actually queue it
  1095. // if there's numbers in the prompt array it will be treated as an array of tokens
  1096. if (task.data.count("prompt") != 0 && task.data.at("prompt").size() > 1) {
  1097. bool numbers = false;
  1098. for (const auto& e : task.data.at("prompt")) {
  1099. if (e.is_number()) {
  1100. numbers = true;
  1101. break;
  1102. }
  1103. }
  1104. // NOTE: split_multiprompt_task() does not handle a mix of strings and numbers,
  1105. // it will completely stall the server. I don't know where the bug for this is.
  1106. //
  1107. // if there are numbers, it needs to be treated like a single prompt,
  1108. // queue_tasks handles a mix of strings and numbers just fine.
  1109. if (numbers) {
  1110. queue_tasks.post(task);
  1111. } else {
  1112. split_multiprompt_task(task_id, task);
  1113. }
  1114. } else {
  1115. // an empty prompt can make slot become buggy
  1116. if (task.data.contains("prompt") && task.data["prompt"].is_string() && task.data["prompt"].get<std::string>().empty()) {
  1117. task.data["prompt"] = " "; // add a space so that we have one token
  1118. }
  1119. queue_tasks.post(task);
  1120. }
  1121. }
  1122. // for multiple images processing
  1123. bool ingest_images(server_slot &slot, int n_batch)
  1124. {
  1125. int image_idx = 0;
  1126. while (image_idx < (int) slot.images.size())
  1127. {
  1128. slot_image &img = slot.images[image_idx];
  1129. // process prefix prompt
  1130. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch)
  1131. {
  1132. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  1133. llama_batch batch_view = {
  1134. n_tokens,
  1135. batch.token + i,
  1136. nullptr,
  1137. batch.pos + i,
  1138. batch.n_seq_id + i,
  1139. batch.seq_id + i,
  1140. batch.logits + i,
  1141. 0, 0, 0, // unused
  1142. };
  1143. if (llama_decode(ctx, batch_view))
  1144. {
  1145. LOG_TEE("%s : failed to eval\n", __func__);
  1146. return false;
  1147. }
  1148. }
  1149. // process image with llm
  1150. for (int i = 0; i < img.image_tokens; i += n_batch)
  1151. {
  1152. int n_eval = img.image_tokens - i;
  1153. if (n_eval > n_batch)
  1154. {
  1155. n_eval = n_batch;
  1156. }
  1157. const int n_embd = llama_n_embd(model);
  1158. llama_batch batch_img = {
  1159. n_eval,
  1160. nullptr,
  1161. (img.image_embedding + i * n_embd),
  1162. nullptr,
  1163. nullptr,
  1164. nullptr,
  1165. nullptr,
  1166. slot.n_past,
  1167. 1, 0
  1168. };
  1169. if (llama_decode(ctx, batch_img))
  1170. {
  1171. LOG_TEE("%s : failed to eval image\n", __func__);
  1172. return false;
  1173. }
  1174. slot.n_past += n_eval;
  1175. }
  1176. image_idx++;
  1177. llama_batch_clear(batch);
  1178. // append prefix of next image
  1179. const auto json_prompt = (image_idx >= (int) slot.images.size()) ?
  1180. slot.params.input_suffix : // no more images, then process suffix prompt
  1181. (json)(slot.images[image_idx].prefix_prompt);
  1182. std::vector<llama_token> append_tokens = tokenize(json_prompt, false); // has next image
  1183. for (int i = 0; i < (int) append_tokens.size(); ++i)
  1184. {
  1185. llama_batch_add(batch, append_tokens[i], system_tokens.size() + slot.n_past, { slot.id }, true);
  1186. slot.n_past += 1;
  1187. }
  1188. }
  1189. return true;
  1190. }
  1191. void request_cancel(int task_id)
  1192. {
  1193. task_server task;
  1194. task.type = TASK_TYPE_CANCEL;
  1195. task.target_id = task_id;
  1196. queue_tasks.post(task);
  1197. }
  1198. void split_multiprompt_task(int multitask_id, task_server& multiprompt_task)
  1199. {
  1200. int prompt_count = multiprompt_task.data.at("prompt").size();
  1201. if (prompt_count <= 1) {
  1202. send_error(multiprompt_task, "error while handling multiple prompts");
  1203. return;
  1204. }
  1205. // generate all the ID for subtask
  1206. std::vector<int> subtask_ids(prompt_count);
  1207. for (int i = 0; i < prompt_count; i++)
  1208. {
  1209. subtask_ids[i] = queue_tasks.get_new_id();
  1210. }
  1211. // queue up the multitask so we can track its subtask progression
  1212. queue_tasks.add_multitask(multitask_id, subtask_ids);
  1213. // add subtasks
  1214. for (int i = 0; i < prompt_count; i++)
  1215. {
  1216. json subtask_data = multiprompt_task.data;
  1217. subtask_data["prompt"] = subtask_data["prompt"][i];
  1218. // subtasks inherit everything else (infill mode, embedding mode, etc.)
  1219. request_completion(subtask_ids[i], subtask_data, multiprompt_task.infill_mode, multiprompt_task.embedding_mode, multitask_id);
  1220. }
  1221. }
  1222. void process_single_task(task_server& task)
  1223. {
  1224. switch (task.type)
  1225. {
  1226. case TASK_TYPE_COMPLETION: {
  1227. server_slot *slot = get_slot(json_value(task.data, "slot_id", -1));
  1228. if (slot == nullptr)
  1229. {
  1230. // if no slot is available, we defer this task for processing later
  1231. LOG_VERBOSE("no slot is available", {{"task_id", task.id}});
  1232. queue_tasks.defer(task);
  1233. break;
  1234. }
  1235. if (task.data.contains("system_prompt"))
  1236. {
  1237. if (!all_slots_are_idle) {
  1238. send_error(task, "system prompt can only be updated when all slots are idle");
  1239. break;
  1240. }
  1241. system_prompt_process(task.data["system_prompt"]);
  1242. // reset cache_tokens for all slots
  1243. for (server_slot &slot : slots)
  1244. {
  1245. slot.cache_tokens.clear();
  1246. slot.n_past = 0;
  1247. slot.n_past_se = 0;
  1248. }
  1249. }
  1250. slot->reset();
  1251. slot->infill = task.infill_mode;
  1252. slot->embedding = task.embedding_mode;
  1253. slot->task_id = task.id;
  1254. slot->multitask_id = task.multitask_id;
  1255. if (!launch_slot_with_data(slot, task.data))
  1256. {
  1257. // send error result
  1258. send_error(task, "internal_error");
  1259. break;
  1260. }
  1261. } break;
  1262. case TASK_TYPE_CANCEL: { // release slot linked with the task id
  1263. for (auto & slot : slots)
  1264. {
  1265. if (slot.task_id == task.target_id)
  1266. {
  1267. slot.release();
  1268. break;
  1269. }
  1270. }
  1271. } break;
  1272. case TASK_TYPE_NEXT_RESPONSE: {
  1273. // do nothing
  1274. } break;
  1275. case TASK_TYPE_METRICS: {
  1276. json slots_data = json::array();
  1277. int n_idle_slots = 0;
  1278. int n_processing_slots = 0;
  1279. for (server_slot &slot: slots) {
  1280. json slot_data = get_formated_generation(slot);
  1281. slot_data["id"] = slot.id;
  1282. slot_data["task_id"] = slot.task_id;
  1283. slot_data["state"] = slot.state;
  1284. slot_data["prompt"] = slot.prompt;
  1285. slot_data["next_token"] = {
  1286. {"has_next_token", slot.has_next_token},
  1287. {"n_remain", slot.n_remaining},
  1288. {"num_tokens_predicted", slot.n_decoded},
  1289. {"stopped_eos", slot.stopped_eos},
  1290. {"stopped_word", slot.stopped_word},
  1291. {"stopped_limit", slot.stopped_limit},
  1292. {"stopping_word", slot.stopping_word},
  1293. };
  1294. if (slot_data["state"] == IDLE) {
  1295. n_idle_slots++;
  1296. } else {
  1297. n_processing_slots++;
  1298. }
  1299. slots_data.push_back(slot_data);
  1300. }
  1301. LOG_INFO("slot data", {
  1302. {"task_id", task.id},
  1303. {"n_idle_slots", n_idle_slots},
  1304. {"n_processing_slots", n_processing_slots}
  1305. });
  1306. LOG_VERBOSE("slot data", {
  1307. {"task_id", task.id},
  1308. {"n_idle_slots", n_idle_slots},
  1309. {"n_processing_slots", n_processing_slots},
  1310. {"slots", slots_data}
  1311. });
  1312. task_result res;
  1313. res.id = task.id;
  1314. res.multitask_id = task.multitask_id;
  1315. res.stop = true;
  1316. res.error = false;
  1317. res.result_json = {
  1318. { "idle", n_idle_slots },
  1319. { "processing", n_processing_slots },
  1320. { "deferred", queue_tasks.queue_tasks_deferred.size() },
  1321. { "n_prompt_tokens_processed_total", metrics.n_prompt_tokens_processed_total},
  1322. { "n_tokens_predicted_total", metrics.n_tokens_predicted_total},
  1323. { "n_prompt_tokens_processed", metrics.n_prompt_tokens_processed},
  1324. { "t_prompt_processing", metrics.t_prompt_processing},
  1325. { "n_tokens_predicted", metrics.n_tokens_predicted},
  1326. { "t_tokens_generation", metrics.t_tokens_generation},
  1327. { "kv_cache_tokens_count", llama_get_kv_cache_token_count(ctx)},
  1328. { "kv_cache_used_cells", llama_get_kv_cache_used_cells(ctx)},
  1329. { "slots", slots_data },
  1330. };
  1331. metrics.reset_bucket();
  1332. queue_results.send(res);
  1333. } break;
  1334. }
  1335. }
  1336. void on_finish_multitask(task_multi& multitask)
  1337. {
  1338. // all subtasks done == multitask is done
  1339. task_result result;
  1340. result.id = multitask.id;
  1341. result.stop = true;
  1342. result.error = false;
  1343. // collect json results into one json result
  1344. std::vector<json> result_jsons;
  1345. for (auto& subres : multitask.results)
  1346. {
  1347. result_jsons.push_back(subres.result_json);
  1348. result.error = result.error && subres.error;
  1349. }
  1350. result.result_json = json{ { "results", result_jsons } };
  1351. queue_results.send(result);
  1352. }
  1353. bool update_slots() {
  1354. if (system_need_update)
  1355. {
  1356. LOG_INFO("updating system prompt", {});
  1357. system_prompt_update();
  1358. }
  1359. llama_batch_clear(batch);
  1360. if (all_slots_are_idle)
  1361. {
  1362. if (system_prompt.empty() && clean_kv_cache)
  1363. {
  1364. LOG_INFO("all slots are idle and system prompt is empty, clear the KV cache", {});
  1365. kv_cache_clear();
  1366. }
  1367. return true;
  1368. }
  1369. LOG_VERBOSE("posting NEXT_RESPONSE", {});
  1370. task_server task;
  1371. task.type = TASK_TYPE_NEXT_RESPONSE;
  1372. task.target_id = -1;
  1373. queue_tasks.post(task);
  1374. for (server_slot &slot : slots)
  1375. {
  1376. if (slot.ga_n == 1)
  1377. {
  1378. if (slot.is_processing() && system_tokens.size() + slot.cache_tokens.size() >= (size_t) slot.n_ctx)
  1379. {
  1380. // Shift context
  1381. const int n_keep = slot.params.n_keep + add_bos_token;
  1382. const int n_left = (int) system_tokens.size() + slot.n_past - n_keep;
  1383. const int n_discard = n_left / 2;
  1384. LOG_INFO("slot context shift", {
  1385. {"slot_id", slot.id},
  1386. {"task_id", slot.task_id},
  1387. {"n_keep", n_keep},
  1388. {"n_left", n_left},
  1389. {"n_discard", n_discard},
  1390. {"n_ctx", n_ctx},
  1391. {"n_past", slot.n_past},
  1392. {"n_system_tokens", system_tokens.size()},
  1393. {"n_cache_tokens", slot.cache_tokens.size()}
  1394. });
  1395. llama_kv_cache_seq_rm (ctx, slot.id, n_keep , n_keep + n_discard);
  1396. llama_kv_cache_seq_add(ctx, slot.id, n_keep + n_discard, system_tokens.size() + slot.n_past, -n_discard);
  1397. for (size_t i = n_keep + n_discard; i < slot.cache_tokens.size(); i++)
  1398. {
  1399. slot.cache_tokens[i - n_discard] = slot.cache_tokens[i];
  1400. }
  1401. slot.cache_tokens.resize(slot.cache_tokens.size() - n_discard);
  1402. slot.n_past -= n_discard;
  1403. slot.truncated = true;
  1404. }
  1405. }
  1406. }
  1407. // decode any currently ongoing sequences
  1408. LOG_VERBOSE("decoding ongoing sequences", {});
  1409. for (auto & slot : slots)
  1410. {
  1411. // release the slot
  1412. if (slot.command == RELEASE)
  1413. {
  1414. slot.state = IDLE;
  1415. slot.command = NONE;
  1416. slot.t_last_used = ggml_time_us();
  1417. LOG_INFO("slot released", {
  1418. {"slot_id", slot.id},
  1419. {"task_id", slot.task_id},
  1420. {"n_ctx", n_ctx},
  1421. {"n_past", slot.n_past},
  1422. {"n_system_tokens", system_tokens.size()},
  1423. {"n_cache_tokens", slot.cache_tokens.size()},
  1424. {"truncated", slot.truncated}
  1425. });
  1426. queue_tasks.notify_slot_changed();
  1427. continue;
  1428. }
  1429. if (slot.state == IDLE)
  1430. {
  1431. continue;
  1432. }
  1433. slot.i_batch = batch.n_tokens;
  1434. const int32_t slot_npast = slot.n_past_se > 0 ? slot.n_past_se : slot.n_past;
  1435. // TODO: we always have to take into account the "system_tokens"
  1436. // this is not great and needs to be improved somehow
  1437. llama_batch_add(batch, slot.sampled, system_tokens.size() + slot_npast, { slot.id }, true);
  1438. slot.n_past += 1;
  1439. }
  1440. // process in chunks of params.n_batch
  1441. int32_t n_batch = params.n_batch;
  1442. // assign workload to the slots
  1443. if (params.cont_batching || batch.n_tokens == 0)
  1444. {
  1445. for (auto & slot : slots)
  1446. {
  1447. const bool has_prompt = slot.prompt.is_array() || (slot.prompt.is_string() && !slot.prompt.get<std::string>().empty()) || !slot.images.empty();
  1448. // empty prompt passed -> release the slot and send empty response
  1449. // note: infill mode allows empty prompt
  1450. if (slot.state == IDLE && slot.command == LOAD_PROMPT && !has_prompt && !slot.infill)
  1451. {
  1452. slot.release();
  1453. slot.print_timings();
  1454. send_final_response(slot);
  1455. continue;
  1456. }
  1457. // need process the prompt
  1458. if (slot.state == IDLE && slot.command == LOAD_PROMPT)
  1459. {
  1460. slot.state = PROCESSING;
  1461. slot.command = NONE;
  1462. std::vector<llama_token> prompt_tokens;
  1463. slot.t_start_process_prompt = ggml_time_us();
  1464. slot.t_start_genereration = 0;
  1465. if (slot.infill)
  1466. {
  1467. bool suff_rm_leading_spc = true;
  1468. if (params.input_suffix.find_first_of(' ') == 0 && params.input_suffix.size() > 1)
  1469. {
  1470. params.input_suffix.erase(0, 1);
  1471. suff_rm_leading_spc = false;
  1472. }
  1473. auto prefix_tokens = tokenize(slot.params.input_prefix, false);
  1474. auto suffix_tokens = tokenize(slot.params.input_suffix, false);
  1475. const int space_token = 29871; // TODO: this should not be hardcoded
  1476. if (suff_rm_leading_spc && !suffix_tokens.empty() && suffix_tokens[0] == space_token) {
  1477. suffix_tokens.erase(suffix_tokens.begin());
  1478. }
  1479. prefix_tokens.insert(prefix_tokens.begin(), llama_token_prefix(model));
  1480. prefix_tokens.insert(prefix_tokens.begin(), llama_token_bos(model)); // always add BOS
  1481. prefix_tokens.insert(prefix_tokens.end(), llama_token_suffix(model));
  1482. prefix_tokens.insert(prefix_tokens.end(), suffix_tokens.begin(), suffix_tokens.end());
  1483. prefix_tokens.push_back(llama_token_middle(model));
  1484. prompt_tokens = prefix_tokens;
  1485. }
  1486. else
  1487. {
  1488. prompt_tokens = tokenize(slot.prompt, system_prompt.empty() && add_bos_token); // add BOS if there isn't system prompt
  1489. }
  1490. slot.n_prompt_tokens = prompt_tokens.size();
  1491. if (slot.params.n_keep < 0)
  1492. {
  1493. slot.params.n_keep = slot.n_prompt_tokens;
  1494. }
  1495. slot.params.n_keep = std::min(slot.n_ctx - 4, slot.params.n_keep);
  1496. // if input prompt is too big, truncate it, if group attention self-extend is disabled
  1497. if (slot.ga_n == 1 && slot.n_prompt_tokens >= slot.n_ctx)
  1498. {
  1499. const int n_left = slot.n_ctx - slot.params.n_keep;
  1500. const int n_block_size = n_left / 2;
  1501. const int erased_blocks = (slot.n_prompt_tokens - slot.params.n_keep - n_block_size) / n_block_size;
  1502. std::vector<llama_token> new_tokens(
  1503. prompt_tokens.begin(),
  1504. prompt_tokens.begin() + slot.params.n_keep);
  1505. new_tokens.insert(
  1506. new_tokens.end(),
  1507. prompt_tokens.begin() + slot.params.n_keep + erased_blocks * n_block_size,
  1508. prompt_tokens.end());
  1509. LOG_VERBOSE("input truncated", {
  1510. {"n_ctx", slot.n_ctx},
  1511. {"n_keep", slot.params.n_keep},
  1512. {"n_left", n_left},
  1513. {"new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend())},
  1514. });
  1515. slot.truncated = true;
  1516. prompt_tokens = new_tokens;
  1517. slot.n_prompt_tokens = prompt_tokens.size();
  1518. GGML_ASSERT(slot.n_prompt_tokens < slot.n_ctx);
  1519. }
  1520. if (!slot.params.cache_prompt)
  1521. {
  1522. llama_sampling_reset(slot.ctx_sampling);
  1523. slot.n_past = 0;
  1524. slot.n_past_se = 0;
  1525. slot.ga_i = 0;
  1526. slot.n_prompt_tokens_processed = slot.n_prompt_tokens;
  1527. }
  1528. else
  1529. {
  1530. // push the prompt into the sampling context (do not apply grammar)
  1531. for (auto &token : prompt_tokens)
  1532. {
  1533. llama_sampling_accept(slot.ctx_sampling, ctx, token, false);
  1534. }
  1535. slot.n_past = common_part(slot.cache_tokens, prompt_tokens);
  1536. // the last token of the cache is not in the KV cache until the next call to llama_decode
  1537. // (it was sampled, pushed into the "cache_tokens", but not yet put in the context)
  1538. if (slot.n_past > 0 && slot.n_past == (int32_t) slot.cache_tokens.size())
  1539. {
  1540. slot.n_past -= 1;
  1541. }
  1542. slot.n_prompt_tokens_processed = slot.n_prompt_tokens - slot.n_past;
  1543. if (slot.ga_n != 1)
  1544. {
  1545. int ga_i = 0;
  1546. int32_t ga_n = slot.ga_n;
  1547. int32_t ga_w = slot.ga_w;
  1548. int32_t slot_npast = 0;
  1549. for (int k = 0; k < slot.n_past; ++k)
  1550. {
  1551. while (slot_npast >= ga_i + ga_w) {
  1552. const int bd = (ga_w/ga_n)*(ga_n - 1);
  1553. slot_npast -= bd;
  1554. ga_i += ga_w/ga_n;
  1555. }
  1556. slot_npast++;
  1557. }
  1558. slot.n_past_se = slot_npast;
  1559. slot.ga_i = ga_i;
  1560. }
  1561. LOG_INFO("slot progression", {
  1562. { "slot_id", slot.id },
  1563. { "task_id", slot.task_id },
  1564. { "n_past", slot.n_past },
  1565. { "n_past_se", slot.n_past_se },
  1566. { "ga_i", slot.ga_i },
  1567. { "n_prompt_tokens_processed", slot.n_prompt_tokens_processed }
  1568. });
  1569. }
  1570. slot.cache_tokens = prompt_tokens;
  1571. if (slot.n_past == slot.n_prompt_tokens && slot.n_past > 0)
  1572. {
  1573. // we have to evaluate at least 1 token to generate logits.
  1574. LOG_INFO("we have to evaluate at least 1 token to generate logits", {
  1575. { "slot_id", slot.id },
  1576. { "task_id", slot.task_id }
  1577. });
  1578. slot.n_past--;
  1579. if (slot.ga_i > 0)
  1580. {
  1581. slot.n_past_se--;
  1582. }
  1583. }
  1584. int p0 = (int) system_tokens.size() + slot.n_past;
  1585. LOG_INFO("kv cache rm [p0, end)", {
  1586. { "slot_id", slot.id },
  1587. { "task_id", slot.task_id },
  1588. { "p0", p0 }
  1589. });
  1590. llama_kv_cache_seq_rm(ctx, slot.id, p0, -1);
  1591. LOG_VERBOSE("prompt ingested", {
  1592. {"n_past", slot.n_past},
  1593. {"cached", tokens_to_str(ctx, slot.cache_tokens.cbegin(), slot.cache_tokens.cbegin() + slot.n_past)},
  1594. {"to_eval", tokens_to_str(ctx, slot.cache_tokens.cbegin() + slot.n_past, slot.cache_tokens.cend())},
  1595. });
  1596. const bool has_images = process_images(slot);
  1597. // process the prefix of first image
  1598. std::vector<llama_token> prefix_tokens = has_images ? tokenize(slot.images[0].prefix_prompt, add_bos_token) : prompt_tokens;
  1599. int32_t slot_npast = slot.n_past_se > 0 ? slot.n_past_se : slot.n_past;
  1600. int32_t ga_i = slot.ga_i;
  1601. int32_t ga_n = slot.ga_n;
  1602. int32_t ga_w = slot.ga_w;
  1603. for (; slot.n_past < (int) prefix_tokens.size(); ++slot.n_past)
  1604. {
  1605. if (slot.ga_n != 1)
  1606. {
  1607. while (slot_npast >= ga_i + ga_w) {
  1608. const int bd = (ga_w/ga_n)*(ga_n - 1);
  1609. slot_npast -= bd;
  1610. ga_i += ga_w/ga_n;
  1611. }
  1612. }
  1613. llama_batch_add(batch, prefix_tokens[slot.n_past], system_tokens.size() + slot_npast, { slot.id }, false);
  1614. slot_npast++;
  1615. }
  1616. if (has_images && !ingest_images(slot, n_batch))
  1617. {
  1618. LOG_ERROR("failed processing images", {
  1619. {"slot_id", slot.id},
  1620. {"task_id", slot.task_id},
  1621. });
  1622. // FIXME @phymbert: to be properly tested
  1623. // early returning without changing the slot state will block the slot for ever
  1624. // no one at the moment is checking the return value
  1625. return false;
  1626. }
  1627. // extract the logits only for the last token
  1628. if (batch.n_tokens > 0)
  1629. {
  1630. batch.logits[batch.n_tokens - 1] = true;
  1631. }
  1632. slot.n_decoded = 0;
  1633. slot.i_batch = batch.n_tokens - 1;
  1634. }
  1635. }
  1636. }
  1637. if (batch.n_tokens == 0)
  1638. {
  1639. all_slots_are_idle = true;
  1640. return true;
  1641. }
  1642. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch)
  1643. {
  1644. const int32_t n_tokens = std::min(n_batch, batch.n_tokens - i);
  1645. for (auto & slot : slots)
  1646. {
  1647. if (slot.ga_n != 1)
  1648. {
  1649. // context extension via Self-Extend
  1650. while (slot.n_past_se >= slot.ga_i + slot.ga_w)
  1651. {
  1652. const int ib = (slot.ga_n * slot.ga_i) / slot.ga_w;
  1653. const int bd = (slot.ga_w / slot.ga_n) * (slot.ga_n - 1);
  1654. const int dd = (slot.ga_w / slot.ga_n) - ib * bd - slot.ga_w;
  1655. LOG_TEE("\n");
  1656. 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);
  1657. 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);
  1658. 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);
  1659. llama_kv_cache_seq_add(ctx, slot.id, slot.ga_i, slot.n_past_se, ib * bd);
  1660. llama_kv_cache_seq_div(ctx, slot.id, slot.ga_i + ib * bd, slot.ga_i + ib * bd + slot.ga_w,slot.ga_n);
  1661. llama_kv_cache_seq_add(ctx, slot.id, slot.ga_i + ib * bd + slot.ga_w,slot.n_past_se + ib * bd, dd);
  1662. slot.n_past_se -= bd;
  1663. slot.ga_i += slot.ga_w / slot.ga_n;
  1664. 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);
  1665. }
  1666. slot.n_past_se += n_tokens;
  1667. }
  1668. }
  1669. llama_batch batch_view =
  1670. {
  1671. n_tokens,
  1672. batch.token + i,
  1673. nullptr,
  1674. batch.pos + i,
  1675. batch.n_seq_id + i,
  1676. batch.seq_id + i,
  1677. batch.logits + i,
  1678. 0, 0, 0, // unused
  1679. };
  1680. const int ret = llama_decode(ctx, batch_view);
  1681. if (ret != 0)
  1682. {
  1683. if (n_batch == 1 || ret < 0)
  1684. {
  1685. // if you get here, it means the KV cache is full - try increasing it via the context size
  1686. LOG_TEE("%s : failed to decode the batch, n_batch = %d, ret = %d\n", __func__, n_batch, ret);
  1687. return false;
  1688. }
  1689. LOG_TEE("%s : failed to find free space in the KV cache, retrying with smaller n_batch = %d\n", __func__, n_batch / 2);
  1690. // retry with half the batch size to try to find a free slot in the KV cache
  1691. n_batch /= 2;
  1692. i -= n_batch;
  1693. continue;
  1694. }
  1695. for (auto & slot : slots)
  1696. {
  1697. if (slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens))
  1698. {
  1699. continue;
  1700. }
  1701. // prompt evaluated for embedding
  1702. if (slot.embedding)
  1703. {
  1704. send_embedding(slot, batch_view);
  1705. slot.release();
  1706. slot.i_batch = -1;
  1707. continue;
  1708. }
  1709. completion_token_output result;
  1710. const llama_token id = llama_sampling_sample(slot.ctx_sampling, ctx, NULL, slot.i_batch - i);
  1711. llama_sampling_accept(slot.ctx_sampling, ctx, id, true);
  1712. slot.n_decoded += 1;
  1713. if (slot.n_decoded == 1)
  1714. {
  1715. slot.t_start_genereration = ggml_time_us();
  1716. slot.t_prompt_processing = (slot.t_start_genereration - slot.t_start_process_prompt) / 1e3;
  1717. metrics.on_prompt_eval(slot);
  1718. }
  1719. llama_token_data_array cur_p = { slot.ctx_sampling->cur.data(), slot.ctx_sampling->cur.size(), false };
  1720. result.tok = id;
  1721. const int32_t n_probs = slot.sparams.n_probs;
  1722. if (slot.sparams.temp <= 0 && n_probs > 0)
  1723. {
  1724. // for llama_sample_token_greedy we need to sort candidates
  1725. llama_sample_softmax(ctx, &cur_p);
  1726. }
  1727. for (size_t i = 0; i < std::min(cur_p.size, (size_t)n_probs); ++i)
  1728. {
  1729. result.probs.push_back({cur_p.data[i].id, cur_p.data[i].p});
  1730. }
  1731. if (!process_token(result, slot))
  1732. {
  1733. slot.release();
  1734. slot.print_timings();
  1735. send_final_response(slot);
  1736. metrics.on_prediction(slot);
  1737. }
  1738. slot.i_batch = -1;
  1739. }
  1740. }
  1741. LOG_VERBOSE("slots updated", {});
  1742. return true;
  1743. }
  1744. json model_meta() {
  1745. return json{
  1746. {"vocab_type", llama_vocab_type(model)},
  1747. {"n_vocab", llama_n_vocab(model)},
  1748. {"n_ctx_train", llama_n_ctx_train(model)},
  1749. {"n_embd", llama_n_embd(model)},
  1750. {"n_params", llama_model_n_params(model)},
  1751. {"size", llama_model_size(model)},
  1752. };
  1753. }
  1754. };
  1755. static void server_print_usage(const char *argv0, const gpt_params &params,
  1756. const server_params &sparams)
  1757. {
  1758. printf("usage: %s [options]\n", argv0);
  1759. printf("\n");
  1760. printf("options:\n");
  1761. printf(" -h, --help show this help message and exit\n");
  1762. printf(" -v, --verbose verbose output (default: %s)\n", server_verbose ? "enabled" : "disabled");
  1763. printf(" -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  1764. printf(" -tb N, --threads-batch N number of threads to use during batch and prompt processing (default: same as --threads)\n");
  1765. printf(" --threads-http N number of threads in the http server pool to process requests (default: max(hardware concurrency - 1, --parallel N + 2))\n");
  1766. printf(" -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  1767. printf(" --rope-scaling {none,linear,yarn}\n");
  1768. printf(" RoPE frequency scaling method, defaults to linear unless specified by the model\n");
  1769. printf(" --rope-freq-base N RoPE base frequency (default: loaded from model)\n");
  1770. printf(" --rope-freq-scale N RoPE frequency scaling factor, expands context by a factor of 1/N\n");
  1771. printf(" --yarn-ext-factor N YaRN: extrapolation mix factor (default: 1.0, 0.0 = full interpolation)\n");
  1772. printf(" --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)\n");
  1773. printf(" --yarn-beta-slow N YaRN: high correction dim or alpha (default: %.1f)\n", params.yarn_beta_slow);
  1774. printf(" --yarn-beta-fast N YaRN: low correction dim or beta (default: %.1f)\n", params.yarn_beta_fast);
  1775. printf(" --pooling {none,mean,cls}\n");
  1776. printf(" pooling type for embeddings, use model default if unspecified\n");
  1777. printf(" -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  1778. printf(" --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  1779. printf(" not recommended: doubles context memory required and no measurable increase in quality\n");
  1780. if (llama_supports_mlock())
  1781. {
  1782. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  1783. }
  1784. if (llama_supports_mmap())
  1785. {
  1786. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  1787. }
  1788. printf(" --numa TYPE attempt optimizations that help on some NUMA systems\n");
  1789. printf(" - distribute: spread execution evenly over all nodes\n");
  1790. printf(" - isolate: only spawn threads on CPUs on the node that execution started on\n");
  1791. printf(" - numactl: use the CPU map provided my numactl\n");
  1792. if (llama_supports_gpu_offload()) {
  1793. printf(" -ngl N, --n-gpu-layers N\n");
  1794. printf(" number of layers to store in VRAM\n");
  1795. printf(" -sm SPLIT_MODE, --split-mode SPLIT_MODE\n");
  1796. printf(" how to split the model across multiple GPUs, one of:\n");
  1797. printf(" - none: use one GPU only\n");
  1798. printf(" - layer (default): split layers and KV across GPUs\n");
  1799. printf(" - row: split rows across GPUs\n");
  1800. printf(" -ts SPLIT --tensor-split SPLIT\n");
  1801. printf(" fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1\n");
  1802. printf(" -mg i, --main-gpu i the GPU to use for the model (with split-mode = none),\n");
  1803. printf(" or for intermediate results and KV (with split-mode = row)\n");
  1804. }
  1805. printf(" -m FNAME, --model FNAME\n");
  1806. printf(" model path (default: %s)\n", params.model.c_str());
  1807. printf(" -a ALIAS, --alias ALIAS\n");
  1808. printf(" set an alias for the model, will be added as `model` field in completion response\n");
  1809. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  1810. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  1811. printf(" --host ip address to listen (default (default: %s)\n", sparams.hostname.c_str());
  1812. printf(" --port PORT port to listen (default (default: %d)\n", sparams.port);
  1813. printf(" --path PUBLIC_PATH path from which to serve static files (default %s)\n", sparams.public_path.c_str());
  1814. printf(" --api-key API_KEY optional api key to enhance server security. If set, requests must include this key for access.\n");
  1815. printf(" --api-key-file FNAME path to file containing api keys delimited by new lines. If set, requests must include one of the keys for access.\n");
  1816. printf(" -to N, --timeout N server read/write timeout in seconds (default: %d)\n", sparams.read_timeout);
  1817. printf(" --embedding enable embedding vector output (default: %s)\n", params.embedding ? "enabled" : "disabled");
  1818. printf(" -np N, --parallel N number of slots for process requests (default: %d)\n", params.n_parallel);
  1819. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)\n");
  1820. printf(" -spf FNAME, --system-prompt-file FNAME\n");
  1821. printf(" set a file to load a system prompt (initial prompt of all slots), this is useful for chat applications.\n");
  1822. printf(" -ctk TYPE, --cache-type-k TYPE\n");
  1823. printf(" KV cache data type for K (default: f16)\n");
  1824. printf(" -ctv TYPE, --cache-type-v TYPE\n");
  1825. printf(" KV cache data type for V (default: f16)\n");
  1826. printf(" --mmproj MMPROJ_FILE path to a multimodal projector file for LLaVA.\n");
  1827. printf(" --log-format log output format: json or text (default: json)\n");
  1828. printf(" --log-disable disables logging to a file.\n");
  1829. printf(" --slots-endpoint-disable disables slots monitoring endpoint.\n");
  1830. printf(" --metrics enable prometheus compatible metrics endpoint (default: %s).\n", sparams.metrics_endpoint ? "enabled" : "disabled");
  1831. printf("\n");
  1832. printf(" -n, --n-predict maximum tokens to predict (default: %d)\n", params.n_predict);
  1833. printf(" --override-kv KEY=TYPE:VALUE\n");
  1834. printf(" advanced option to override model metadata by key. may be specified multiple times.\n");
  1835. printf(" types: int, float, bool. example: --override-kv tokenizer.ggml.add_bos_token=bool:false\n");
  1836. printf(" -gan N, --grp-attn-n N set the group attention factor to extend context size through self-extend(default: 1=disabled), used together with group attention width `--grp-attn-w`\n");
  1837. printf(" -gaw N, --grp-attn-w N set the group attention width to extend context size through self-extend(default: 512), used together with group attention factor `--grp-attn-n`\n");
  1838. printf(" --chat-template JINJA_TEMPLATE\n");
  1839. printf(" set custom jinja chat template (default: template taken from model's metadata)\n");
  1840. printf(" Note: only commonly used templates are accepted, since we don't have jinja parser\n");
  1841. printf("\n");
  1842. }
  1843. static void server_params_parse(int argc, char **argv, server_params &sparams,
  1844. gpt_params &params, llama_server_context& llama)
  1845. {
  1846. gpt_params default_params;
  1847. server_params default_sparams;
  1848. std::string arg;
  1849. bool invalid_param = false;
  1850. for (int i = 1; i < argc; i++)
  1851. {
  1852. arg = argv[i];
  1853. if (arg == "--port")
  1854. {
  1855. if (++i >= argc)
  1856. {
  1857. invalid_param = true;
  1858. break;
  1859. }
  1860. sparams.port = std::stoi(argv[i]);
  1861. }
  1862. else if (arg == "--host")
  1863. {
  1864. if (++i >= argc)
  1865. {
  1866. invalid_param = true;
  1867. break;
  1868. }
  1869. sparams.hostname = argv[i];
  1870. }
  1871. else if (arg == "--path")
  1872. {
  1873. if (++i >= argc)
  1874. {
  1875. invalid_param = true;
  1876. break;
  1877. }
  1878. sparams.public_path = argv[i];
  1879. }
  1880. else if (arg == "--api-key")
  1881. {
  1882. if (++i >= argc)
  1883. {
  1884. invalid_param = true;
  1885. break;
  1886. }
  1887. sparams.api_keys.emplace_back(argv[i]);
  1888. }
  1889. else if (arg == "--api-key-file")
  1890. {
  1891. if (++i >= argc)
  1892. {
  1893. invalid_param = true;
  1894. break;
  1895. }
  1896. std::ifstream key_file(argv[i]);
  1897. if (!key_file) {
  1898. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1899. invalid_param = true;
  1900. break;
  1901. }
  1902. std::string key;
  1903. while (std::getline(key_file, key)) {
  1904. if (key.size() > 0) {
  1905. sparams.api_keys.push_back(key);
  1906. }
  1907. }
  1908. key_file.close();
  1909. }
  1910. else if (arg == "--timeout" || arg == "-to")
  1911. {
  1912. if (++i >= argc)
  1913. {
  1914. invalid_param = true;
  1915. break;
  1916. }
  1917. sparams.read_timeout = std::stoi(argv[i]);
  1918. sparams.write_timeout = std::stoi(argv[i]);
  1919. }
  1920. else if (arg == "-m" || arg == "--model")
  1921. {
  1922. if (++i >= argc)
  1923. {
  1924. invalid_param = true;
  1925. break;
  1926. }
  1927. params.model = argv[i];
  1928. }
  1929. else if (arg == "-a" || arg == "--alias")
  1930. {
  1931. if (++i >= argc)
  1932. {
  1933. invalid_param = true;
  1934. break;
  1935. }
  1936. params.model_alias = argv[i];
  1937. }
  1938. else if (arg == "-h" || arg == "--help")
  1939. {
  1940. server_print_usage(argv[0], default_params, default_sparams);
  1941. exit(0);
  1942. }
  1943. else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size")
  1944. {
  1945. if (++i >= argc)
  1946. {
  1947. invalid_param = true;
  1948. break;
  1949. }
  1950. params.n_ctx = std::stoi(argv[i]);
  1951. }
  1952. else if (arg == "--rope-scaling")
  1953. {
  1954. if (++i >= argc)
  1955. {
  1956. invalid_param = true;
  1957. break;
  1958. }
  1959. std::string value(argv[i]);
  1960. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE; }
  1961. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_LINEAR; }
  1962. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_YARN; }
  1963. else { invalid_param = true; break; }
  1964. }
  1965. else if (arg == "--rope-freq-base")
  1966. {
  1967. if (++i >= argc)
  1968. {
  1969. invalid_param = true;
  1970. break;
  1971. }
  1972. params.rope_freq_base = std::stof(argv[i]);
  1973. }
  1974. else if (arg == "--rope-freq-scale")
  1975. {
  1976. if (++i >= argc)
  1977. {
  1978. invalid_param = true;
  1979. break;
  1980. }
  1981. params.rope_freq_scale = std::stof(argv[i]);
  1982. }
  1983. else if (arg == "--yarn-ext-factor")
  1984. {
  1985. if (++i >= argc) {
  1986. invalid_param = true;
  1987. break;
  1988. }
  1989. params.yarn_ext_factor = std::stof(argv[i]);
  1990. }
  1991. else if (arg == "--yarn-attn-factor")
  1992. {
  1993. if (++i >= argc) {
  1994. invalid_param = true;
  1995. break;
  1996. }
  1997. params.yarn_attn_factor = std::stof(argv[i]);
  1998. }
  1999. else if (arg == "--yarn-beta-fast")
  2000. {
  2001. if (++i >= argc) {
  2002. invalid_param = true;
  2003. break;
  2004. }
  2005. params.yarn_beta_fast = std::stof(argv[i]);
  2006. }
  2007. else if (arg == "--yarn-beta-slow")
  2008. {
  2009. if (++i >= argc) {
  2010. invalid_param = true;
  2011. break;
  2012. }
  2013. params.yarn_beta_slow = std::stof(argv[i]);
  2014. }
  2015. else if (arg == "--pooling")
  2016. {
  2017. if (++i >= argc) {
  2018. invalid_param = true;
  2019. break;
  2020. }
  2021. std::string value(argv[i]);
  2022. /**/ if (value == "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
  2023. else if (value == "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
  2024. else if (value == "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
  2025. else { invalid_param = true; break; }
  2026. }
  2027. else if (arg == "--threads" || arg == "-t")
  2028. {
  2029. if (++i >= argc)
  2030. {
  2031. invalid_param = true;
  2032. break;
  2033. }
  2034. params.n_threads = std::stoi(argv[i]);
  2035. }
  2036. else if (arg == "--grp-attn-n" || arg == "-gan")
  2037. {
  2038. if (++i >= argc) {
  2039. invalid_param = true;
  2040. break;
  2041. }
  2042. params.grp_attn_n = std::stoi(argv[i]);
  2043. }
  2044. else if (arg == "--grp-attn-w" || arg == "-gaw")
  2045. {
  2046. if (++i >= argc)
  2047. {
  2048. invalid_param = true;
  2049. break;
  2050. }
  2051. params.grp_attn_w = std::stoi(argv[i]);
  2052. }
  2053. else if (arg == "--threads-batch" || arg == "-tb")
  2054. {
  2055. if (++i >= argc)
  2056. {
  2057. invalid_param = true;
  2058. break;
  2059. }
  2060. params.n_threads_batch = std::stoi(argv[i]);
  2061. }
  2062. else if (arg == "--threads-http")
  2063. {
  2064. if (++i >= argc)
  2065. {
  2066. invalid_param = true;
  2067. break;
  2068. }
  2069. sparams.n_threads_http = std::stoi(argv[i]);
  2070. }
  2071. else if (arg == "-b" || arg == "--batch-size")
  2072. {
  2073. if (++i >= argc)
  2074. {
  2075. invalid_param = true;
  2076. break;
  2077. }
  2078. params.n_batch = std::stoi(argv[i]);
  2079. }
  2080. else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers")
  2081. {
  2082. if (++i >= argc)
  2083. {
  2084. invalid_param = true;
  2085. break;
  2086. }
  2087. if (llama_supports_gpu_offload()) {
  2088. params.n_gpu_layers = std::stoi(argv[i]);
  2089. } else {
  2090. LOG_WARNING("Not compiled with GPU offload support, --n-gpu-layers option will be ignored. "
  2091. "See main README.md for information on enabling GPU BLAS support",
  2092. {{"n_gpu_layers", params.n_gpu_layers}});
  2093. }
  2094. }
  2095. else if (arg == "--split-mode" || arg == "-sm")
  2096. {
  2097. if (++i >= argc) {
  2098. invalid_param = true;
  2099. break;
  2100. }
  2101. std::string arg_next = argv[i];
  2102. if (arg_next == "none")
  2103. {
  2104. params.split_mode = LLAMA_SPLIT_MODE_NONE;
  2105. }
  2106. else if (arg_next == "layer")
  2107. {
  2108. params.split_mode = LLAMA_SPLIT_MODE_LAYER;
  2109. }
  2110. else if (arg_next == "row")
  2111. {
  2112. params.split_mode = LLAMA_SPLIT_MODE_ROW;
  2113. }
  2114. else {
  2115. invalid_param = true;
  2116. break;
  2117. }
  2118. #ifndef GGML_USE_CUBLAS
  2119. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. Setting the split mode has no effect.\n");
  2120. #endif // GGML_USE_CUBLAS
  2121. }
  2122. else if (arg == "--tensor-split" || arg == "-ts")
  2123. {
  2124. if (++i >= argc)
  2125. {
  2126. invalid_param = true;
  2127. break;
  2128. }
  2129. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL)
  2130. std::string arg_next = argv[i];
  2131. // split string by , and /
  2132. const std::regex regex{R"([,/]+)"};
  2133. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  2134. std::vector<std::string> split_arg{it, {}};
  2135. GGML_ASSERT(split_arg.size() <= llama_max_devices());
  2136. for (size_t i_device = 0; i_device < llama_max_devices(); ++i_device)
  2137. {
  2138. if (i_device < split_arg.size())
  2139. {
  2140. params.tensor_split[i_device] = std::stof(split_arg[i_device]);
  2141. }
  2142. else
  2143. {
  2144. params.tensor_split[i_device] = 0.0f;
  2145. }
  2146. }
  2147. #else
  2148. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n", {});
  2149. #endif // GGML_USE_CUBLAS
  2150. }
  2151. else if (arg == "--main-gpu" || arg == "-mg")
  2152. {
  2153. if (++i >= argc)
  2154. {
  2155. invalid_param = true;
  2156. break;
  2157. }
  2158. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL)
  2159. params.main_gpu = std::stoi(argv[i]);
  2160. #else
  2161. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.", {});
  2162. #endif
  2163. }
  2164. else if (arg == "--lora")
  2165. {
  2166. if (++i >= argc)
  2167. {
  2168. invalid_param = true;
  2169. break;
  2170. }
  2171. params.lora_adapter.emplace_back(argv[i], 1.0f);
  2172. params.use_mmap = false;
  2173. }
  2174. else if (arg == "--lora-scaled")
  2175. {
  2176. if (++i >= argc)
  2177. {
  2178. invalid_param = true;
  2179. break;
  2180. }
  2181. const char * lora_adapter = argv[i];
  2182. if (++i >= argc)
  2183. {
  2184. invalid_param = true;
  2185. break;
  2186. }
  2187. params.lora_adapter.emplace_back(lora_adapter, std::stof(argv[i]));
  2188. params.use_mmap = false;
  2189. }
  2190. else if (arg == "--lora-base")
  2191. {
  2192. if (++i >= argc)
  2193. {
  2194. invalid_param = true;
  2195. break;
  2196. }
  2197. params.lora_base = argv[i];
  2198. }
  2199. else if (arg == "-v" || arg == "--verbose")
  2200. {
  2201. #if SERVER_VERBOSE != 1
  2202. LOG_WARNING("server.cpp is not built with verbose logging.", {});
  2203. #else
  2204. server_verbose = true;
  2205. #endif
  2206. }
  2207. else if (arg == "--mlock")
  2208. {
  2209. params.use_mlock = true;
  2210. }
  2211. else if (arg == "--no-mmap")
  2212. {
  2213. params.use_mmap = false;
  2214. }
  2215. else if (arg == "--numa") {
  2216. if (++i >= argc) {
  2217. invalid_param = true;
  2218. break;
  2219. } else {
  2220. std::string value(argv[i]);
  2221. /**/ if (value == "distribute" || value == "" ) { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
  2222. else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
  2223. else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
  2224. else { invalid_param = true; break; }
  2225. }
  2226. }
  2227. else if (arg == "--embedding")
  2228. {
  2229. params.embedding = true;
  2230. }
  2231. else if (arg == "-cb" || arg == "--cont-batching")
  2232. {
  2233. params.cont_batching = true;
  2234. }
  2235. else if (arg == "-np" || arg == "--parallel")
  2236. {
  2237. if (++i >= argc)
  2238. {
  2239. invalid_param = true;
  2240. break;
  2241. }
  2242. params.n_parallel = std::stoi(argv[i]);
  2243. } else if (arg == "-n" || arg == "--n-predict")
  2244. {
  2245. if (++i >= argc)
  2246. {
  2247. invalid_param = true;
  2248. break;
  2249. }
  2250. params.n_predict = std::stoi(argv[i]);
  2251. } else if (arg == "-spf" || arg == "--system-prompt-file")
  2252. {
  2253. if (++i >= argc)
  2254. {
  2255. invalid_param = true;
  2256. break;
  2257. }
  2258. std::ifstream file(argv[i]);
  2259. if (!file) {
  2260. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  2261. invalid_param = true;
  2262. break;
  2263. }
  2264. std::string systm_content;
  2265. std::copy(
  2266. std::istreambuf_iterator<char>(file),
  2267. std::istreambuf_iterator<char>(),
  2268. std::back_inserter(systm_content)
  2269. );
  2270. llama.system_prompt_process(json::parse(systm_content));
  2271. }
  2272. else if (arg == "-ctk" || arg == "--cache-type-k") {
  2273. params.cache_type_k = argv[++i];
  2274. }
  2275. else if (arg == "-ctv" || arg == "--cache-type-v") {
  2276. params.cache_type_v = argv[++i];
  2277. }
  2278. else if(arg == "--mmproj")
  2279. {
  2280. if (++i >= argc)
  2281. {
  2282. invalid_param = true;
  2283. break;
  2284. }
  2285. params.mmproj = argv[i];
  2286. }
  2287. else if (arg == "--log-format")
  2288. {
  2289. if (++i >= argc)
  2290. {
  2291. invalid_param = true;
  2292. break;
  2293. }
  2294. if (std::strcmp(argv[i], "json") == 0)
  2295. {
  2296. server_log_json = true;
  2297. }
  2298. else if (std::strcmp(argv[i], "text") == 0)
  2299. {
  2300. server_log_json = false;
  2301. }
  2302. else
  2303. {
  2304. invalid_param = true;
  2305. break;
  2306. }
  2307. }
  2308. else if (arg == "--log-disable")
  2309. {
  2310. log_set_target(stdout);
  2311. LOG_INFO("logging to file is disabled.", {});
  2312. }
  2313. else if (arg == "--slots-endpoint-disable")
  2314. {
  2315. sparams.slots_endpoint = false;
  2316. }
  2317. else if (arg == "--metrics")
  2318. {
  2319. sparams.metrics_endpoint = true;
  2320. }
  2321. else if (arg == "--chat-template")
  2322. {
  2323. if (++i >= argc)
  2324. {
  2325. invalid_param = true;
  2326. break;
  2327. }
  2328. if (!verify_custom_template(argv[i])) {
  2329. fprintf(stderr, "error: the supplied chat template is not supported: %s\n", argv[i]);
  2330. fprintf(stderr, "note: llama.cpp does not use jinja parser, we only support commonly used templates\n");
  2331. invalid_param = true;
  2332. break;
  2333. }
  2334. sparams.chat_template = argv[i];
  2335. }
  2336. else if (arg == "--override-kv")
  2337. {
  2338. if (++i >= argc) {
  2339. invalid_param = true;
  2340. break;
  2341. }
  2342. char * sep = strchr(argv[i], '=');
  2343. if (sep == nullptr || sep - argv[i] >= 128) {
  2344. fprintf(stderr, "error: Malformed KV override: %s\n", argv[i]);
  2345. invalid_param = true;
  2346. break;
  2347. }
  2348. struct llama_model_kv_override kvo;
  2349. std::strncpy(kvo.key, argv[i], sep - argv[i]);
  2350. kvo.key[sep - argv[i]] = 0;
  2351. sep++;
  2352. if (strncmp(sep, "int:", 4) == 0) {
  2353. sep += 4;
  2354. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  2355. kvo.int_value = std::atol(sep);
  2356. } else if (strncmp(sep, "float:", 6) == 0) {
  2357. sep += 6;
  2358. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
  2359. kvo.float_value = std::atof(sep);
  2360. } else if (strncmp(sep, "bool:", 5) == 0) {
  2361. sep += 5;
  2362. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
  2363. if (std::strcmp(sep, "true") == 0) {
  2364. kvo.bool_value = true;
  2365. } else if (std::strcmp(sep, "false") == 0) {
  2366. kvo.bool_value = false;
  2367. } else {
  2368. fprintf(stderr, "error: Invalid boolean value for KV override: %s\n", argv[i]);
  2369. invalid_param = true;
  2370. break;
  2371. }
  2372. } else {
  2373. fprintf(stderr, "error: Invalid type for KV override: %s\n", argv[i]);
  2374. invalid_param = true;
  2375. break;
  2376. }
  2377. params.kv_overrides.push_back(kvo);
  2378. }
  2379. else
  2380. {
  2381. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  2382. server_print_usage(argv[0], default_params, default_sparams);
  2383. exit(1);
  2384. }
  2385. }
  2386. if (!params.kv_overrides.empty()) {
  2387. params.kv_overrides.emplace_back();
  2388. params.kv_overrides.back().key[0] = 0;
  2389. }
  2390. if (invalid_param)
  2391. {
  2392. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  2393. server_print_usage(argv[0], default_params, default_sparams);
  2394. exit(1);
  2395. }
  2396. }
  2397. /* llama.cpp completion api semantics */
  2398. static json format_partial_response(
  2399. llama_server_context &llama, server_slot *slot, const std::string &content, const std::vector<completion_token_output> &probs
  2400. ) {
  2401. json res = json
  2402. {
  2403. {"content", content },
  2404. {"stop", false},
  2405. {"slot_id", slot->id },
  2406. {"multimodal", llama.multimodal }
  2407. };
  2408. if (slot->sparams.n_probs > 0)
  2409. {
  2410. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  2411. }
  2412. return res;
  2413. }
  2414. static json format_tokenizer_response(const std::vector<llama_token> &tokens)
  2415. {
  2416. return json {
  2417. {"tokens", tokens}
  2418. };
  2419. }
  2420. static json format_detokenized_response(std::string content)
  2421. {
  2422. return json {
  2423. {"content", content}
  2424. };
  2425. }
  2426. static void log_server_request(const httplib::Request &req, const httplib::Response &res)
  2427. {
  2428. // skip GH copilot requests when using default port
  2429. if (req.path == "/v1/health" || req.path == "/v1/completions")
  2430. {
  2431. return;
  2432. }
  2433. LOG_INFO("request", {
  2434. {"remote_addr", req.remote_addr},
  2435. {"remote_port", req.remote_port},
  2436. {"status", res.status},
  2437. {"method", req.method},
  2438. {"path", req.path},
  2439. {"params", req.params},
  2440. });
  2441. LOG_VERBOSE("request", {
  2442. {"request", req.body},
  2443. {"response", res.body},
  2444. });
  2445. }
  2446. static void append_to_generated_text_from_generated_token_probs(llama_server_context &llama, server_slot *slot)
  2447. {
  2448. auto & gtps = slot->generated_token_probs;
  2449. auto translator = token_translator{llama.ctx};
  2450. auto add_strlen = [=](size_t sum, const completion_token_output & cto) { return sum + translator(cto).size(); };
  2451. const size_t len = std::accumulate(gtps.begin(), gtps.end(), size_t(0), add_strlen);
  2452. if (slot->generated_text.capacity() < slot->generated_text.size() + len)
  2453. {
  2454. slot->generated_text.reserve(slot->generated_text.size() + len);
  2455. }
  2456. for (const completion_token_output & cto : gtps)
  2457. {
  2458. slot->generated_text += translator(cto);
  2459. }
  2460. }
  2461. std::function<void(int)> shutdown_handler;
  2462. std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
  2463. inline void signal_handler(int signal) {
  2464. if (is_terminating.test_and_set()) {
  2465. // in case it hangs, we can force terminate the server by hitting Ctrl+C twice
  2466. // this is for better developer experience, we can remove when the server is stable enough
  2467. fprintf(stderr, "Received second interrupt, terminating immediately.\n");
  2468. exit(1);
  2469. }
  2470. shutdown_handler(signal);
  2471. }
  2472. int main(int argc, char **argv)
  2473. {
  2474. #if SERVER_VERBOSE != 1
  2475. log_disable();
  2476. #endif
  2477. // own arguments required by this example
  2478. gpt_params params;
  2479. server_params sparams;
  2480. // struct that contains llama context and inference
  2481. llama_server_context llama;
  2482. server_params_parse(argc, argv, sparams, params, llama);
  2483. if (params.model_alias == "unknown")
  2484. {
  2485. params.model_alias = params.model;
  2486. }
  2487. llama_backend_init();
  2488. llama_numa_init(params.numa);
  2489. LOG_INFO("build info", {{"build", LLAMA_BUILD_NUMBER},
  2490. {"commit", LLAMA_COMMIT}});
  2491. LOG_INFO("system info", {
  2492. {"n_threads", params.n_threads},
  2493. {"n_threads_batch", params.n_threads_batch},
  2494. {"total_threads", std::thread::hardware_concurrency()},
  2495. {"system_info", llama_print_system_info()},
  2496. });
  2497. httplib::Server svr;
  2498. std::atomic<server_state> state{SERVER_STATE_LOADING_MODEL};
  2499. svr.set_default_headers({{"Server", "llama.cpp"}});
  2500. // CORS preflight
  2501. svr.Options(R"(.*)", [](const httplib::Request &req, httplib::Response &res) {
  2502. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2503. res.set_header("Access-Control-Allow-Credentials", "true");
  2504. res.set_header("Access-Control-Allow-Methods", "POST");
  2505. res.set_header("Access-Control-Allow-Headers", "*");
  2506. });
  2507. svr.Get("/health", [&](const httplib::Request& req, httplib::Response& res) {
  2508. server_state current_state = state.load();
  2509. switch(current_state) {
  2510. case SERVER_STATE_READY: {
  2511. // request slots data using task queue
  2512. task_server task;
  2513. task.id = llama.queue_tasks.get_new_id();
  2514. task.type = TASK_TYPE_METRICS;
  2515. task.target_id = -1;
  2516. llama.queue_results.add_waiting_task_id(task.id);
  2517. llama.queue_tasks.post(task);
  2518. // get the result
  2519. task_result result = llama.queue_results.recv(task.id);
  2520. llama.queue_results.remove_waiting_task_id(task.id);
  2521. int n_idle_slots = result.result_json["idle"];
  2522. int n_processing_slots = result.result_json["processing"];
  2523. json health = {
  2524. {"status", "ok"},
  2525. {"slots_idle", n_idle_slots},
  2526. {"slots_processing", n_processing_slots}};
  2527. res.status = 200; // HTTP OK
  2528. if (sparams.slots_endpoint && req.has_param("include_slots")) {
  2529. health["slots"] = result.result_json["slots"];
  2530. }
  2531. if (n_idle_slots == 0) {
  2532. health["status"] = "no slot available";
  2533. if (req.has_param("fail_on_no_slot")) {
  2534. res.status = 503; // HTTP Service Unavailable
  2535. }
  2536. }
  2537. res.set_content(health.dump(), "application/json");
  2538. break;
  2539. }
  2540. case SERVER_STATE_LOADING_MODEL:
  2541. res.set_content(R"({"status": "loading model"})", "application/json");
  2542. res.status = 503; // HTTP Service Unavailable
  2543. break;
  2544. case SERVER_STATE_ERROR:
  2545. res.set_content(R"({"status": "error", "error": "Model failed to load"})", "application/json");
  2546. res.status = 500; // HTTP Internal Server Error
  2547. break;
  2548. }
  2549. });
  2550. if (sparams.slots_endpoint) {
  2551. svr.Get("/slots", [&](const httplib::Request&, httplib::Response& res) {
  2552. // request slots data using task queue
  2553. task_server task;
  2554. task.id = llama.queue_tasks.get_new_id();
  2555. task.type = TASK_TYPE_METRICS;
  2556. task.target_id = -1;
  2557. llama.queue_results.add_waiting_task_id(task.id);
  2558. llama.queue_tasks.post(task);
  2559. // get the result
  2560. task_result result = llama.queue_results.recv(task.id);
  2561. llama.queue_results.remove_waiting_task_id(task.id);
  2562. res.set_content(result.result_json["slots"].dump(), "application/json");
  2563. res.status = 200; // HTTP OK
  2564. });
  2565. }
  2566. if (sparams.metrics_endpoint) {
  2567. svr.Get("/metrics", [&](const httplib::Request&, httplib::Response& res) {
  2568. // request slots data using task queue
  2569. task_server task;
  2570. task.id = llama.queue_tasks.get_new_id();
  2571. task.type = TASK_TYPE_METRICS;
  2572. task.target_id = -1;
  2573. llama.queue_results.add_waiting_task_id(task.id);
  2574. llama.queue_tasks.post(task);
  2575. // get the result
  2576. task_result result = llama.queue_results.recv(task.id);
  2577. llama.queue_results.remove_waiting_task_id(task.id);
  2578. json data = result.result_json;
  2579. uint64_t n_prompt_tokens_processed = data["n_prompt_tokens_processed"];
  2580. uint64_t t_prompt_processing = data["t_prompt_processing"];
  2581. uint64_t n_tokens_predicted = data["n_tokens_predicted"];
  2582. uint64_t t_tokens_generation = data["t_tokens_generation"];
  2583. int32_t kv_cache_used_cells = data["kv_cache_used_cells"];
  2584. // metrics definition: https://prometheus.io/docs/practices/naming/#metric-names
  2585. json all_metrics_def = json {
  2586. {"counter", {{
  2587. {"name", "prompt_tokens_total"},
  2588. {"help", "Number of prompt tokens processed."},
  2589. {"value", data["n_prompt_tokens_processed_total"]}
  2590. }, {
  2591. {"name", "tokens_predicted_total"},
  2592. {"help", "Number of generation tokens processed."},
  2593. {"value", data["n_tokens_predicted_total"]}
  2594. }}},
  2595. {"gauge", {{
  2596. {"name", "prompt_tokens_seconds"},
  2597. {"help", "Average prompt throughput in tokens/s."},
  2598. {"value", n_prompt_tokens_processed ? 1e3 / t_prompt_processing * n_prompt_tokens_processed : 0}
  2599. },{
  2600. {"name", "predicted_tokens_seconds"},
  2601. {"help", "Average generation throughput in tokens/s."},
  2602. {"value", n_tokens_predicted ? 1e3 / t_tokens_generation * n_tokens_predicted : 0}
  2603. },{
  2604. {"name", "kv_cache_usage_ratio"},
  2605. {"help", "KV-cache usage. 1 means 100 percent usage."},
  2606. {"value", 1. * kv_cache_used_cells / params.n_ctx}
  2607. },{
  2608. {"name", "kv_cache_tokens"},
  2609. {"help", "KV-cache tokens."},
  2610. {"value", data["kv_cache_tokens_count"]}
  2611. },{
  2612. {"name", "requests_processing"},
  2613. {"help", "Number of request processing."},
  2614. {"value", data["processing"]}
  2615. },{
  2616. {"name", "requests_deferred"},
  2617. {"help", "Number of request deferred."},
  2618. {"value", data["deferred"]}
  2619. }}}
  2620. };
  2621. std::stringstream prometheus;
  2622. for (const auto& el : all_metrics_def.items()) {
  2623. const auto& type = el.key();
  2624. const auto& metrics_def = el.value();
  2625. for (const auto& metric_def : metrics_def) {
  2626. std::string name = metric_def["name"];
  2627. std::string help = metric_def["help"];
  2628. auto value = json_value(metric_def, "value", 0);
  2629. prometheus << "# HELP llamacpp:" << name << " " << help << "\n"
  2630. << "# TYPE llamacpp:" << name << " " << type << "\n"
  2631. << "llamacpp:" << name << " " << value << "\n";
  2632. }
  2633. }
  2634. res.set_content(prometheus.str(), "text/plain; version=0.0.4");
  2635. res.status = 200; // HTTP OK
  2636. });
  2637. }
  2638. svr.set_logger(log_server_request);
  2639. svr.set_exception_handler([](const httplib::Request &, httplib::Response &res, std::exception_ptr ep)
  2640. {
  2641. const char fmt[] = "500 Internal Server Error\n%s";
  2642. char buf[BUFSIZ];
  2643. try
  2644. {
  2645. std::rethrow_exception(std::move(ep));
  2646. }
  2647. catch (std::exception &e)
  2648. {
  2649. snprintf(buf, sizeof(buf), fmt, e.what());
  2650. }
  2651. catch (...)
  2652. {
  2653. snprintf(buf, sizeof(buf), fmt, "Unknown Exception");
  2654. }
  2655. res.set_content(buf, "text/plain; charset=utf-8");
  2656. res.status = 500;
  2657. });
  2658. svr.set_error_handler([](const httplib::Request &, httplib::Response &res)
  2659. {
  2660. if (res.status == 401)
  2661. {
  2662. res.set_content("Unauthorized", "text/plain; charset=utf-8");
  2663. }
  2664. if (res.status == 400)
  2665. {
  2666. res.set_content("Invalid request", "text/plain; charset=utf-8");
  2667. }
  2668. else if (res.status == 404)
  2669. {
  2670. res.set_content("File Not Found", "text/plain; charset=utf-8");
  2671. res.status = 404;
  2672. }
  2673. });
  2674. // set timeouts and change hostname and port
  2675. svr.set_read_timeout (sparams.read_timeout);
  2676. svr.set_write_timeout(sparams.write_timeout);
  2677. if (!svr.bind_to_port(sparams.hostname, sparams.port))
  2678. {
  2679. fprintf(stderr, "\ncouldn't bind to server socket: hostname=%s port=%d\n\n", sparams.hostname.c_str(), sparams.port);
  2680. return 1;
  2681. }
  2682. // Set the base directory for serving static files
  2683. svr.set_base_dir(sparams.public_path);
  2684. std::unordered_map<std::string, std::string> log_data;
  2685. log_data["hostname"] = sparams.hostname;
  2686. log_data["port"] = std::to_string(sparams.port);
  2687. if (sparams.api_keys.size() == 1) {
  2688. log_data["api_key"] = "api_key: ****" + sparams.api_keys[0].substr(sparams.api_keys[0].length() - 4);
  2689. } else if (sparams.api_keys.size() > 1) {
  2690. log_data["api_key"] = "api_key: " + std::to_string(sparams.api_keys.size()) + " keys loaded";
  2691. }
  2692. // load the model
  2693. if (!llama.load_model(params))
  2694. {
  2695. state.store(SERVER_STATE_ERROR);
  2696. return 1;
  2697. } else {
  2698. llama.initialize();
  2699. state.store(SERVER_STATE_READY);
  2700. LOG_INFO("model loaded", {});
  2701. }
  2702. const auto model_meta = llama.model_meta();
  2703. if (sparams.chat_template.empty()) { // custom chat template is not supplied
  2704. // check if the template comes with the model is supported by us
  2705. llama.validate_model_chat_template(sparams);
  2706. }
  2707. // Middleware for API key validation
  2708. auto validate_api_key = [&sparams](const httplib::Request &req, httplib::Response &res) -> bool {
  2709. // If API key is not set, skip validation
  2710. if (sparams.api_keys.empty()) {
  2711. return true;
  2712. }
  2713. // Check for API key in the header
  2714. auto auth_header = req.get_header_value("Authorization");
  2715. std::string prefix = "Bearer ";
  2716. if (auth_header.substr(0, prefix.size()) == prefix) {
  2717. std::string received_api_key = auth_header.substr(prefix.size());
  2718. if (std::find(sparams.api_keys.begin(), sparams.api_keys.end(), received_api_key) != sparams.api_keys.end()) {
  2719. return true; // API key is valid
  2720. }
  2721. }
  2722. // API key is invalid or not provided
  2723. res.set_content("Unauthorized: Invalid API Key", "text/plain; charset=utf-8");
  2724. res.status = 401; // Unauthorized
  2725. LOG_WARNING("Unauthorized: Invalid API Key", {});
  2726. return false;
  2727. };
  2728. // this is only called if no index.html is found in the public --path
  2729. svr.Get("/", [](const httplib::Request &, httplib::Response &res)
  2730. {
  2731. res.set_content("server running", "text/plain; charset=utf-8");
  2732. res.status = 200; // Unauthorized
  2733. return true;
  2734. });
  2735. svr.Post("/completion", [&llama, &validate_api_key](const httplib::Request &req, httplib::Response &res)
  2736. {
  2737. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2738. if (!validate_api_key(req, res)) {
  2739. return;
  2740. }
  2741. json data = json::parse(req.body);
  2742. const int task_id = llama.queue_tasks.get_new_id();
  2743. llama.queue_results.add_waiting_task_id(task_id);
  2744. llama.request_completion(task_id, data, false, false, -1);
  2745. if (!json_value(data, "stream", false)) {
  2746. std::string completion_text;
  2747. task_result result = llama.queue_results.recv(task_id);
  2748. if (!result.error && result.stop) {
  2749. res.set_content(result.result_json.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  2750. }
  2751. else
  2752. {
  2753. res.status = 404;
  2754. res.set_content(result.result_json["content"], "text/plain; charset=utf-8");
  2755. }
  2756. llama.queue_results.remove_waiting_task_id(task_id);
  2757. } else {
  2758. const auto chunked_content_provider = [task_id, &llama](size_t, httplib::DataSink & sink)
  2759. {
  2760. while (true)
  2761. {
  2762. task_result result = llama.queue_results.recv(task_id);
  2763. if (!result.error) {
  2764. const std::string str =
  2765. "data: " +
  2766. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace) +
  2767. "\n\n";
  2768. LOG_VERBOSE("data stream", {
  2769. { "to_send", str }
  2770. });
  2771. if (!sink.write(str.c_str(), str.size()))
  2772. {
  2773. llama.queue_results.remove_waiting_task_id(task_id);
  2774. return false;
  2775. }
  2776. if (result.stop) {
  2777. break;
  2778. }
  2779. } else {
  2780. const std::string str =
  2781. "error: " +
  2782. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace) +
  2783. "\n\n";
  2784. LOG_VERBOSE("data stream", {
  2785. { "to_send", str }
  2786. });
  2787. if (!sink.write(str.c_str(), str.size()))
  2788. {
  2789. llama.queue_results.remove_waiting_task_id(task_id);
  2790. return false;
  2791. }
  2792. break;
  2793. }
  2794. }
  2795. llama.queue_results.remove_waiting_task_id(task_id);
  2796. sink.done();
  2797. return true;
  2798. };
  2799. auto on_complete = [task_id, &llama] (bool)
  2800. {
  2801. // cancel
  2802. llama.request_cancel(task_id);
  2803. llama.queue_results.remove_waiting_task_id(task_id);
  2804. };
  2805. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2806. }
  2807. });
  2808. svr.Post("/tokenize", [&llama](const httplib::Request &req, httplib::Response &res)
  2809. {
  2810. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2811. const json body = json::parse(req.body);
  2812. std::vector<llama_token> tokens;
  2813. if (body.count("content") != 0)
  2814. {
  2815. tokens = llama.tokenize(body["content"], false);
  2816. }
  2817. const json data = format_tokenizer_response(tokens);
  2818. return res.set_content(data.dump(), "application/json; charset=utf-8");
  2819. });
  2820. svr.Post("/detokenize", [&llama](const httplib::Request &req, httplib::Response &res)
  2821. {
  2822. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2823. const json body = json::parse(req.body);
  2824. std::string content;
  2825. if (body.count("tokens") != 0)
  2826. {
  2827. const std::vector<llama_token> tokens = body["tokens"];
  2828. content = tokens_to_str(llama.ctx, tokens.cbegin(), tokens.cend());
  2829. }
  2830. const json data = format_detokenized_response(content);
  2831. return res.set_content(data.dump(), "application/json; charset=utf-8");
  2832. });
  2833. svr.Post("/embedding", [&llama](const httplib::Request &req, httplib::Response &res)
  2834. {
  2835. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2836. const json body = json::parse(req.body);
  2837. json prompt;
  2838. if (body.count("content") != 0)
  2839. {
  2840. prompt = body["content"];
  2841. }
  2842. else
  2843. {
  2844. prompt = "";
  2845. }
  2846. json image_data;
  2847. if (body.count("image_data") != 0) {
  2848. image_data = body["image_data"];
  2849. }
  2850. else
  2851. {
  2852. image_data = "";
  2853. }
  2854. // create and queue the task
  2855. const int task_id = llama.queue_tasks.get_new_id();
  2856. llama.queue_results.add_waiting_task_id(task_id);
  2857. llama.request_completion(task_id, { {"prompt", prompt}, { "n_predict", 0}, {"image_data", image_data} }, false, true, -1);
  2858. // get the result
  2859. task_result result = llama.queue_results.recv(task_id);
  2860. llama.queue_results.remove_waiting_task_id(task_id);
  2861. // send the result
  2862. return res.set_content(result.result_json.dump(), "application/json; charset=utf-8");
  2863. });
  2864. // GG: if I put the main loop inside a thread, it crashes on the first request when build in Debug!?
  2865. // "Bus error: 10" - this is on macOS, it does not crash on Linux
  2866. //std::thread t2([&]()
  2867. /*{
  2868. bool running = true;
  2869. while (running)
  2870. {
  2871. running = llama.update_slots();
  2872. }
  2873. }*/
  2874. //);
  2875. if (sparams.n_threads_http < 1) {
  2876. // +2 threads for monitoring endpoints
  2877. sparams.n_threads_http = std::max(params.n_parallel + 2, (int32_t) std::thread::hardware_concurrency() - 1);
  2878. }
  2879. log_data["n_threads_http"] = std::to_string(sparams.n_threads_http);
  2880. svr.new_task_queue = [&sparams] { return new httplib::ThreadPool(sparams.n_threads_http); };
  2881. LOG_INFO("HTTP server listening", log_data);
  2882. // run the HTTP server in a thread - see comment below
  2883. std::thread t([&]()
  2884. {
  2885. if (!svr.listen_after_bind())
  2886. {
  2887. state.store(SERVER_STATE_ERROR);
  2888. return 1;
  2889. }
  2890. return 0;
  2891. });
  2892. llama.queue_tasks.on_new_task(std::bind(
  2893. &llama_server_context::process_single_task, &llama, std::placeholders::_1));
  2894. llama.queue_tasks.on_finish_multitask(std::bind(
  2895. &llama_server_context::on_finish_multitask, &llama, std::placeholders::_1));
  2896. llama.queue_tasks.on_run_slots(std::bind(
  2897. &llama_server_context::update_slots, &llama));
  2898. llama.queue_results.on_multitask_update(std::bind(
  2899. &llama_server_queue::update_multitask,
  2900. &llama.queue_tasks,
  2901. std::placeholders::_1,
  2902. std::placeholders::_2,
  2903. std::placeholders::_3
  2904. ));
  2905. shutdown_handler = [&](int) {
  2906. llama.queue_tasks.terminate();
  2907. };
  2908. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  2909. struct sigaction sigint_action;
  2910. sigint_action.sa_handler = signal_handler;
  2911. sigemptyset (&sigint_action.sa_mask);
  2912. sigint_action.sa_flags = 0;
  2913. sigaction(SIGINT, &sigint_action, NULL);
  2914. #elif defined (_WIN32)
  2915. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  2916. return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
  2917. };
  2918. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  2919. #endif
  2920. llama.queue_tasks.start_loop();
  2921. svr.stop();
  2922. t.join();
  2923. llama_backend_free();
  2924. return 0;
  2925. }