server.cpp 121 KB

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