server.cpp 135 KB

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