1
0

server.cpp 154 KB

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