server.cpp 124 KB

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