server.cpp 122 KB

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