server.cpp 128 KB

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