server.cpp 121 KB

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