server.cpp 141 KB

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