server.cpp 124 KB

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