server.cpp 132 KB

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