1
0

server.cpp 136 KB

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