server.cpp 154 KB

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