1
0

server.cpp 135 KB

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