1
0

server.cpp 128 KB

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