server.cpp 123 KB

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