server.cpp 139 KB

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