server.cpp 154 KB

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