server.cpp 136 KB

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