1
0

server.cpp 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "grammar-parser.h"
  4. #include "utils.hpp"
  5. #include "oai.hpp"
  6. #include "../llava/clip.h"
  7. #include "stb_image.h"
  8. #ifndef NDEBUG
  9. // crash the server in debug mode, otherwise send an http 500 error
  10. #define CPPHTTPLIB_NO_EXCEPTIONS 1
  11. #endif
  12. // increase max payload length to allow use of larger context size
  13. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 1048576
  14. #include "httplib.h"
  15. #include "json.hpp"
  16. // auto generated files (update with ./deps.sh)
  17. #include "index.html.hpp"
  18. #include "index.js.hpp"
  19. #include "completion.js.hpp"
  20. #include "json-schema-to-grammar.mjs.hpp"
  21. #include <cstddef>
  22. #include <thread>
  23. #include <chrono>
  24. #include <condition_variable>
  25. #include <atomic>
  26. #include <signal.h>
  27. using json = nlohmann::json;
  28. struct server_params
  29. {
  30. std::string hostname = "127.0.0.1";
  31. std::vector<std::string> api_keys;
  32. std::string public_path = "examples/server/public";
  33. std::string chat_template = "chatml";
  34. int32_t port = 8080;
  35. int32_t read_timeout = 600;
  36. int32_t write_timeout = 600;
  37. bool slots_endpoint = true;
  38. };
  39. bool server_verbose = false;
  40. static size_t common_part(const std::vector<llama_token> &a, const std::vector<llama_token> &b)
  41. {
  42. size_t i;
  43. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++)
  44. {
  45. }
  46. return i;
  47. }
  48. enum stop_type
  49. {
  50. STOP_FULL,
  51. STOP_PARTIAL,
  52. };
  53. static bool ends_with(const std::string &str, const std::string &suffix)
  54. {
  55. return str.size() >= suffix.size() &&
  56. 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  57. }
  58. static size_t find_partial_stop_string(const std::string &stop,
  59. const std::string &text)
  60. {
  61. if (!text.empty() && !stop.empty())
  62. {
  63. const char text_last_char = text.back();
  64. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--)
  65. {
  66. if (stop[char_index] == text_last_char)
  67. {
  68. const std::string current_partial = stop.substr(0, char_index + 1);
  69. if (ends_with(text, current_partial))
  70. {
  71. return text.size() - char_index - 1;
  72. }
  73. }
  74. }
  75. }
  76. return std::string::npos;
  77. }
  78. // TODO: reuse llama_detokenize
  79. template <class Iter>
  80. static std::string tokens_to_str(llama_context *ctx, Iter begin, Iter end)
  81. {
  82. std::string ret;
  83. for (; begin != end; ++begin)
  84. {
  85. ret += llama_token_to_piece(ctx, *begin);
  86. }
  87. return ret;
  88. }
  89. // format incomplete utf-8 multibyte character for output
  90. static std::string tokens_to_output_formatted_string(const llama_context *ctx, const llama_token token)
  91. {
  92. std::string out = token == -1 ? "" : llama_token_to_piece(ctx, token);
  93. // if the size is 1 and first bit is 1, meaning it's a partial character
  94. // (size > 1 meaning it's already a known token)
  95. if (out.size() == 1 && (out[0] & 0x80) == 0x80)
  96. {
  97. std::stringstream ss;
  98. ss << std::hex << (out[0] & 0xff);
  99. std::string res(ss.str());
  100. out = "byte: \\x" + res;
  101. }
  102. return out;
  103. }
  104. // convert a vector of completion_token_output to json
  105. static json probs_vector_to_json(const llama_context *ctx, const std::vector<completion_token_output> &probs)
  106. {
  107. json out = json::array();
  108. for (const auto &prob : probs)
  109. {
  110. json probs_for_token = json::array();
  111. for (const auto &p : prob.probs)
  112. {
  113. std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
  114. probs_for_token.push_back(json
  115. {
  116. {"tok_str", tok_str},
  117. {"prob", p.prob},
  118. });
  119. }
  120. std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
  121. out.push_back(json{
  122. {"content", tok_str},
  123. {"probs", probs_for_token},
  124. });
  125. }
  126. return out;
  127. }
  128. struct llama_client_slot
  129. {
  130. int id;
  131. int task_id = -1;
  132. struct slot_params params;
  133. slot_state state = IDLE;
  134. slot_command command = NONE;
  135. // used to determine the slot that has been used the longest
  136. int64_t t_last_used = -1;
  137. // generation props
  138. int32_t n_ctx = 0; // context size per slot
  139. int32_t n_past = 0;
  140. int32_t n_decoded = 0;
  141. int32_t n_remaining = -1;
  142. int32_t i_batch = -1;
  143. int32_t n_predict = -1;
  144. int32_t num_prompt_tokens = 0;
  145. int32_t num_prompt_tokens_processed = 0;
  146. json prompt;
  147. std::string generated_text;
  148. llama_token sampled;
  149. std::vector<llama_token> cache_tokens;
  150. std::vector<completion_token_output> generated_token_probs;
  151. bool infill = false;
  152. bool embedding = false;
  153. bool has_next_token = true;
  154. bool truncated = false;
  155. bool stopped_eos = false;
  156. bool stopped_word = false;
  157. bool stopped_limit = false;
  158. bool oaicompat = false;
  159. std::string oaicompat_model;
  160. std::string stopping_word;
  161. // sampling
  162. struct llama_sampling_params sparams;
  163. llama_sampling_context *ctx_sampling = nullptr;
  164. int32_t ga_i = 0; // group-attention state
  165. int32_t ga_n = 1; // group-attention factor
  166. int32_t ga_w = 512; // group-attention width
  167. int32_t n_past_se = 0; // self-extend
  168. // multimodal
  169. std::vector<slot_image> images;
  170. // stats
  171. size_t sent_count = 0;
  172. size_t sent_token_probs_index = 0;
  173. int64_t t_start_process_prompt;
  174. int64_t t_start_genereration;
  175. double t_prompt_processing; // ms
  176. double t_token_generation; // ms
  177. // multitasks
  178. int multitask_id = -1;
  179. void reset() {
  180. num_prompt_tokens = 0;
  181. generated_text = "";
  182. truncated = false;
  183. stopped_eos = false;
  184. stopped_word = false;
  185. stopped_limit = false;
  186. stopping_word = "";
  187. n_past = 0;
  188. sent_count = 0;
  189. sent_token_probs_index = 0;
  190. infill = false;
  191. ga_i = 0;
  192. n_past_se = 0;
  193. generated_token_probs.clear();
  194. for (slot_image & img : images)
  195. {
  196. free(img.image_embedding);
  197. if (img.img_data) {
  198. clip_image_u8_free(img.img_data);
  199. }
  200. img.prefix_prompt = "";
  201. }
  202. images.clear();
  203. }
  204. bool has_budget(gpt_params &global_params) {
  205. if (params.n_predict == -1 && global_params.n_predict == -1)
  206. {
  207. return true; // limitless
  208. }
  209. n_remaining = -1;
  210. if (params.n_predict != -1)
  211. {
  212. n_remaining = params.n_predict - n_decoded;
  213. }
  214. else if (global_params.n_predict != -1)
  215. {
  216. n_remaining = global_params.n_predict - n_decoded;
  217. }
  218. return n_remaining > 0; // no budget
  219. }
  220. bool available() const {
  221. return state == IDLE && command == NONE;
  222. }
  223. bool is_processing() const {
  224. return (state == IDLE && command == LOAD_PROMPT) || state == PROCESSING;
  225. }
  226. void add_token_string(const completion_token_output &token) {
  227. if (command == RELEASE)
  228. {
  229. return;
  230. }
  231. cache_tokens.push_back(token.tok);
  232. generated_token_probs.push_back(token);
  233. }
  234. void release() {
  235. if (state == PROCESSING)
  236. {
  237. t_token_generation = (ggml_time_us() - t_start_genereration) / 1e3;
  238. command = RELEASE;
  239. }
  240. }
  241. json get_formated_timings() {
  242. return json
  243. {
  244. {"prompt_n", num_prompt_tokens_processed},
  245. {"prompt_ms", t_prompt_processing},
  246. {"prompt_per_token_ms", t_prompt_processing / num_prompt_tokens_processed},
  247. {"prompt_per_second", 1e3 / t_prompt_processing * num_prompt_tokens_processed},
  248. {"predicted_n", n_decoded},
  249. {"predicted_ms", t_token_generation},
  250. {"predicted_per_token_ms", t_token_generation / n_decoded},
  251. {"predicted_per_second", 1e3 / t_token_generation * n_decoded},
  252. };
  253. }
  254. void print_timings() const {
  255. LOG_TEE("\n");
  256. LOG_TEE("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  257. __func__, t_prompt_processing, num_prompt_tokens_processed, t_prompt_processing / num_prompt_tokens_processed, 1e3 / t_prompt_processing * num_prompt_tokens_processed);
  258. LOG_TEE("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  259. __func__, t_token_generation, n_decoded,t_token_generation / n_decoded, 1e3 / t_token_generation * n_decoded);
  260. LOG_TEE("%s: total time = %10.2f ms\n", __func__, t_prompt_processing + t_token_generation);
  261. }
  262. };
  263. struct llama_server_context
  264. {
  265. llama_model *model = nullptr;
  266. llama_context *ctx = nullptr;
  267. clip_ctx *clp_ctx = nullptr;
  268. gpt_params params;
  269. llama_batch batch;
  270. bool multimodal = false;
  271. bool clean_kv_cache = true;
  272. bool all_slots_are_idle = false;
  273. bool add_bos_token = true;
  274. int32_t n_ctx; // total context for all clients / slots
  275. // system prompt
  276. bool system_need_update = false;
  277. std::string system_prompt;
  278. std::vector<llama_token> system_tokens;
  279. std::string name_user; // this should be the antiprompt
  280. std::string name_assistant;
  281. // slots / clients
  282. std::vector<llama_client_slot> slots;
  283. json default_generation_settings_for_props;
  284. llama_server_queue queue_tasks;
  285. llama_server_response queue_results;
  286. ~llama_server_context()
  287. {
  288. if (ctx)
  289. {
  290. llama_free(ctx);
  291. ctx = nullptr;
  292. }
  293. if (model)
  294. {
  295. llama_free_model(model);
  296. model = nullptr;
  297. }
  298. }
  299. bool load_model(const gpt_params &params_)
  300. {
  301. params = params_;
  302. if (!params.mmproj.empty()) {
  303. multimodal = true;
  304. LOG_TEE("Multi Modal Mode Enabled");
  305. clp_ctx = clip_model_load(params.mmproj.c_str(), /*verbosity=*/ 1);
  306. if(clp_ctx == nullptr) {
  307. LOG_ERROR("unable to load clip model", {{"model", params.mmproj}});
  308. return false;
  309. }
  310. if (params.n_ctx < 2048) { // request larger context for the image embedding
  311. params.n_ctx = 2048;
  312. }
  313. }
  314. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  315. if (model == nullptr)
  316. {
  317. LOG_ERROR("unable to load model", {{"model", params.model}});
  318. return false;
  319. }
  320. if (multimodal) {
  321. const int n_embd_clip = clip_n_mmproj_embd(clp_ctx);
  322. const int n_embd_llm = llama_n_embd(model);
  323. if (n_embd_clip != n_embd_llm) {
  324. LOG_TEE("%s: embedding dim of the multimodal projector (%d) is not equal to that of LLaMA (%d). Make sure that you use the correct mmproj file.\n", __func__, n_embd_clip, n_embd_llm);
  325. llama_free(ctx);
  326. llama_free_model(model);
  327. return false;
  328. }
  329. }
  330. n_ctx = llama_n_ctx(ctx);
  331. add_bos_token = llama_should_add_bos_token(model);
  332. return true;
  333. }
  334. void initialize() {
  335. // create slots
  336. all_slots_are_idle = true;
  337. const int32_t n_ctx_slot = n_ctx / params.n_parallel;
  338. LOG_TEE("Available slots:\n");
  339. for (int i = 0; i < params.n_parallel; i++)
  340. {
  341. llama_client_slot slot;
  342. slot.id = i;
  343. slot.n_ctx = n_ctx_slot;
  344. slot.n_predict = params.n_predict;
  345. LOG_TEE(" -> Slot %i - max context: %i\n", slot.id, n_ctx_slot);
  346. const int ga_n = params.grp_attn_n;
  347. const int ga_w = params.grp_attn_w;
  348. if (ga_n != 1) {
  349. GGML_ASSERT(ga_n > 0 && "ga_n must be positive"); // NOLINT
  350. GGML_ASSERT(ga_w % ga_n == 0 && "ga_w must be a multiple of ga_n"); // NOLINT
  351. //GGML_ASSERT(n_ctx_train % ga_w == 0 && "n_ctx_train must be a multiple of ga_w"); // NOLINT
  352. //GGML_ASSERT(n_ctx >= n_ctx_train * ga_n && "n_ctx must be at least n_ctx_train * ga_n"); // NOLINT
  353. LOG_TEE(" -> Slot %i - self-extend: ga_n = %d, ga_w = %d\n", slot.id, ga_n, ga_w);
  354. }
  355. slot.ga_i = 0;
  356. slot.ga_n = ga_n;
  357. slot.ga_w = ga_w;
  358. slot.reset();
  359. slots.push_back(slot);
  360. }
  361. default_generation_settings_for_props = get_formated_generation(slots.front());
  362. default_generation_settings_for_props["seed"] = -1;
  363. batch = llama_batch_init(n_ctx, 0, params.n_parallel);
  364. }
  365. std::vector<llama_token> tokenize(const json & json_prompt, bool add_bos) const
  366. {
  367. // TODO: currently, we tokenize using special tokens by default
  368. // this is not always correct (see https://github.com/ggerganov/llama.cpp/pull/4160#issuecomment-1824826216)
  369. // but it's better compared to completely ignoring ChatML and other chat templates
  370. const bool TMP_FORCE_SPECIAL = true;
  371. // If `add_bos` is true, we only add BOS, when json_prompt is a string,
  372. // or the first element of the json_prompt array is a string.
  373. std::vector<llama_token> prompt_tokens;
  374. if (json_prompt.is_array())
  375. {
  376. bool first = true;
  377. for (const auto& p : json_prompt)
  378. {
  379. if (p.is_string())
  380. {
  381. auto s = p.template get<std::string>();
  382. std::vector<llama_token> p;
  383. if (first)
  384. {
  385. p = ::llama_tokenize(ctx, s, add_bos, TMP_FORCE_SPECIAL);
  386. first = false;
  387. }
  388. else
  389. {
  390. p = ::llama_tokenize(ctx, s, false, TMP_FORCE_SPECIAL);
  391. }
  392. prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
  393. }
  394. else
  395. {
  396. if (first)
  397. {
  398. first = false;
  399. }
  400. prompt_tokens.push_back(p.template get<llama_token>());
  401. }
  402. }
  403. }
  404. else
  405. {
  406. auto s = json_prompt.template get<std::string>();
  407. prompt_tokens = ::llama_tokenize(ctx, s, add_bos, TMP_FORCE_SPECIAL);
  408. }
  409. return prompt_tokens;
  410. }
  411. llama_client_slot* get_slot(int id) {
  412. int64_t t_last = ggml_time_us();
  413. llama_client_slot *last_used = nullptr;
  414. for (llama_client_slot & slot : slots)
  415. {
  416. if (slot.id == id && slot.available())
  417. {
  418. return &slot;
  419. }
  420. if (slot.available() && slot.t_last_used < t_last)
  421. {
  422. last_used = &slot;
  423. t_last = slot.t_last_used;
  424. }
  425. }
  426. return last_used;
  427. }
  428. bool launch_slot_with_data(llama_client_slot* &slot, json data) {
  429. slot_params default_params;
  430. llama_sampling_params default_sparams;
  431. if (data.count("__oaicompat") != 0) {
  432. slot->oaicompat = true;
  433. slot->oaicompat_model = json_value(data, "model", std::string(DEFAULT_OAICOMPAT_MODEL));
  434. } else {
  435. slot->oaicompat = false;
  436. slot->oaicompat_model = "";
  437. }
  438. slot->params.stream = json_value(data, "stream", false);
  439. slot->params.cache_prompt = json_value(data, "cache_prompt", false);
  440. slot->params.n_predict = json_value(data, "n_predict", default_params.n_predict);
  441. slot->sparams.top_k = json_value(data, "top_k", default_sparams.top_k);
  442. slot->sparams.top_p = json_value(data, "top_p", default_sparams.top_p);
  443. slot->sparams.min_p = json_value(data, "min_p", default_sparams.min_p);
  444. slot->sparams.tfs_z = json_value(data, "tfs_z", default_sparams.tfs_z);
  445. slot->sparams.typical_p = json_value(data, "typical_p", default_sparams.typical_p);
  446. slot->sparams.temp = json_value(data, "temperature", default_sparams.temp);
  447. slot->sparams.dynatemp_range = json_value(data, "dynatemp_range", default_sparams.dynatemp_range);
  448. slot->sparams.dynatemp_exponent = json_value(data, "dynatemp_exponent", default_sparams.dynatemp_exponent);
  449. slot->sparams.penalty_last_n = json_value(data, "repeat_last_n", default_sparams.penalty_last_n);
  450. slot->sparams.penalty_repeat = json_value(data, "repeat_penalty", default_sparams.penalty_repeat);
  451. slot->sparams.penalty_freq = json_value(data, "frequency_penalty", default_sparams.penalty_freq);
  452. slot->sparams.penalty_present = json_value(data, "presence_penalty", default_sparams.penalty_present);
  453. slot->sparams.mirostat = json_value(data, "mirostat", default_sparams.mirostat);
  454. slot->sparams.mirostat_tau = json_value(data, "mirostat_tau", default_sparams.mirostat_tau);
  455. slot->sparams.mirostat_eta = json_value(data, "mirostat_eta", default_sparams.mirostat_eta);
  456. slot->sparams.penalize_nl = json_value(data, "penalize_nl", default_sparams.penalize_nl);
  457. slot->params.n_keep = json_value(data, "n_keep", slot->params.n_keep);
  458. slot->params.seed = json_value(data, "seed", default_params.seed);
  459. slot->sparams.grammar = json_value(data, "grammar", default_sparams.grammar);
  460. slot->sparams.n_probs = json_value(data, "n_probs", default_sparams.n_probs);
  461. if (slot->n_predict > 0 && slot->params.n_predict > slot->n_predict) {
  462. // Might be better to reject the request with a 400 ?
  463. LOG_WARNING("Max tokens to predict exceeds server configuration", {
  464. {"params.n_predict", slot->params.n_predict},
  465. {"slot.n_predict", slot->n_predict},
  466. });
  467. slot->params.n_predict = slot->n_predict;
  468. }
  469. // infill
  470. if (data.count("input_prefix") != 0)
  471. {
  472. slot->params.input_prefix = data["input_prefix"];
  473. }
  474. else
  475. {
  476. slot->params.input_prefix = "";
  477. }
  478. if (data.count("input_suffix") != 0)
  479. {
  480. slot->params.input_suffix = data["input_suffix"];
  481. }
  482. else
  483. {
  484. slot->params.input_suffix = "";
  485. }
  486. if (data.count("prompt") != 0)
  487. {
  488. slot->prompt = data["prompt"];
  489. }
  490. else
  491. {
  492. slot->prompt = "";
  493. }
  494. slot->sparams.penalty_prompt_tokens.clear();
  495. slot->sparams.use_penalty_prompt_tokens = false;
  496. const auto &penalty_prompt = data.find("penalty_prompt");
  497. if (penalty_prompt != data.end())
  498. {
  499. if (penalty_prompt->is_string())
  500. {
  501. const auto penalty_prompt_string = penalty_prompt->get<std::string>();
  502. auto penalty_tokens = llama_tokenize(model, penalty_prompt_string, false);
  503. slot->sparams.penalty_prompt_tokens.swap(penalty_tokens);
  504. if (slot->params.n_predict > 0)
  505. {
  506. slot->sparams.penalty_prompt_tokens.reserve(slot->sparams.penalty_prompt_tokens.size() + slot->params.n_predict);
  507. }
  508. slot->sparams.use_penalty_prompt_tokens = true;
  509. }
  510. else if (penalty_prompt->is_array())
  511. {
  512. const auto n_tokens = penalty_prompt->size();
  513. slot->sparams.penalty_prompt_tokens.reserve(n_tokens + std::max(0, slot->params.n_predict));
  514. const int n_vocab = llama_n_vocab(model);
  515. for (const auto &penalty_token : *penalty_prompt)
  516. {
  517. if (penalty_token.is_number_integer())
  518. {
  519. const auto tok = penalty_token.get<llama_token>();
  520. if (tok >= 0 && tok < n_vocab)
  521. {
  522. slot->sparams.penalty_prompt_tokens.push_back(tok);
  523. }
  524. }
  525. }
  526. slot->sparams.use_penalty_prompt_tokens = true;
  527. }
  528. }
  529. slot->sparams.logit_bias.clear();
  530. if (json_value(data, "ignore_eos", false))
  531. {
  532. slot->sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  533. }
  534. const auto &logit_bias = data.find("logit_bias");
  535. if (logit_bias != data.end() && logit_bias->is_array())
  536. {
  537. const int n_vocab = llama_n_vocab(model);
  538. for (const auto &el : *logit_bias)
  539. {
  540. if (el.is_array() && el.size() == 2)
  541. {
  542. float bias;
  543. if (el[1].is_number())
  544. {
  545. bias = el[1].get<float>();
  546. }
  547. else if (el[1].is_boolean() && !el[1].get<bool>())
  548. {
  549. bias = -INFINITY;
  550. }
  551. else
  552. {
  553. continue;
  554. }
  555. if (el[0].is_number_integer())
  556. {
  557. llama_token tok = el[0].get<llama_token>();
  558. if (tok >= 0 && tok < n_vocab)
  559. {
  560. slot->sparams.logit_bias[tok] = bias;
  561. }
  562. }
  563. else if (el[0].is_string())
  564. {
  565. auto toks = llama_tokenize(model, el[0].get<std::string>(), false);
  566. for (auto tok : toks)
  567. {
  568. slot->sparams.logit_bias[tok] = bias;
  569. }
  570. }
  571. }
  572. }
  573. }
  574. slot->params.antiprompt.clear();
  575. const auto &stop = data.find("stop");
  576. if (stop != data.end() && stop->is_array())
  577. {
  578. for (const auto &word : *stop)
  579. {
  580. if (!word.empty())
  581. {
  582. slot->params.antiprompt.push_back(word);
  583. }
  584. }
  585. }
  586. const auto &samplers_sequence = data.find("samplers");
  587. if (samplers_sequence != data.end() && samplers_sequence->is_array())
  588. {
  589. std::vector<std::string> sampler_names;
  590. for (const auto &sampler_name : *samplers_sequence)
  591. {
  592. if (sampler_name.is_string())
  593. {
  594. sampler_names.emplace_back(sampler_name);
  595. }
  596. }
  597. slot->sparams.samplers_sequence = sampler_types_from_names(sampler_names, false);
  598. }
  599. else
  600. {
  601. slot->sparams.samplers_sequence = default_sparams.samplers_sequence;
  602. }
  603. if (multimodal)
  604. {
  605. const auto &images_data = data.find("image_data");
  606. if (images_data != data.end() && images_data->is_array())
  607. {
  608. for (const auto &img : *images_data)
  609. {
  610. const std::vector<uint8_t> image_buffer = base64_decode(img["data"].get<std::string>());
  611. slot_image img_sl;
  612. img_sl.id = img.count("id") != 0 ? img["id"].get<int>() : slot->images.size();
  613. img_sl.img_data = clip_image_u8_init();
  614. if (!clip_image_load_from_bytes(image_buffer.data(), image_buffer.size(), img_sl.img_data))
  615. {
  616. LOG_TEE("slot %i - failed to load image [id: %i]\n", slot->id, img_sl.id);
  617. return false;
  618. }
  619. LOG_TEE("slot %i - loaded image\n", slot->id);
  620. img_sl.request_encode_image = true;
  621. slot->images.push_back(img_sl);
  622. }
  623. // process prompt
  624. // example: system prompt [img-102] user [img-103] describe [img-134] -> [{id: 102, prefix: 'system prompt '}, {id: 103, prefix: ' user '}, {id: 134, prefix: ' describe '}]}
  625. if (slot->images.size() > 0 && !slot->prompt.is_array())
  626. {
  627. std::string prompt = slot->prompt.get<std::string>();
  628. size_t pos = 0, begin_prefix = 0;
  629. std::string pattern = "[img-";
  630. while ((pos = prompt.find(pattern, pos)) != std::string::npos) {
  631. size_t end_prefix = pos;
  632. pos += pattern.length();
  633. size_t end_pos = prompt.find(']', pos);
  634. if (end_pos != std::string::npos)
  635. {
  636. std::string image_id = prompt.substr(pos, end_pos - pos);
  637. try
  638. {
  639. int img_id = std::stoi(image_id);
  640. bool found = false;
  641. for (slot_image &img : slot->images)
  642. {
  643. if (img.id == img_id) {
  644. found = true;
  645. img.prefix_prompt = prompt.substr(begin_prefix, end_prefix - begin_prefix);
  646. begin_prefix = end_pos + 1;
  647. break;
  648. }
  649. }
  650. if (!found) {
  651. LOG_TEE("ERROR: Image with id: %i, not found.\n", img_id);
  652. slot->images.clear();
  653. return false;
  654. }
  655. } catch (const std::invalid_argument& e) {
  656. LOG_TEE("Invalid image number id in prompt\n");
  657. slot->images.clear();
  658. return false;
  659. }
  660. }
  661. }
  662. slot->prompt = "";
  663. slot->params.input_suffix = prompt.substr(begin_prefix);
  664. slot->params.cache_prompt = false; // multimodal doesn't support cache prompt
  665. }
  666. }
  667. }
  668. if (slot->ctx_sampling != nullptr)
  669. {
  670. llama_sampling_free(slot->ctx_sampling);
  671. }
  672. slot->ctx_sampling = llama_sampling_init(slot->sparams);
  673. llama_set_rng_seed(ctx, slot->params.seed);
  674. slot->command = LOAD_PROMPT;
  675. all_slots_are_idle = false;
  676. LOG_TEE("slot %i is processing [task id: %i]\n", slot->id, slot->task_id);
  677. return true;
  678. }
  679. void kv_cache_clear() {
  680. // clear the entire KV cache
  681. llama_kv_cache_clear(ctx);
  682. clean_kv_cache = false;
  683. }
  684. void update_system_prompt() {
  685. kv_cache_clear();
  686. system_tokens.clear();
  687. if (!system_prompt.empty()) {
  688. system_tokens = ::llama_tokenize(ctx, system_prompt, add_bos_token);
  689. llama_batch_clear(batch);
  690. for (int i = 0; i < (int)system_tokens.size(); ++i)
  691. {
  692. llama_batch_add(batch, system_tokens[i], i, { 0 }, false);
  693. }
  694. if (llama_decode(ctx, batch) != 0)
  695. {
  696. LOG_TEE("%s: llama_decode() failed\n", __func__);
  697. return;
  698. }
  699. // assign the system KV cache to all parallel sequences
  700. for (int32_t i = 1; i < params.n_parallel; ++i)
  701. {
  702. llama_kv_cache_seq_cp(ctx, 0, i, 0, system_tokens.size());
  703. }
  704. }
  705. LOG_TEE("system prompt updated\n");
  706. system_need_update = false;
  707. }
  708. void notify_system_prompt_changed() {
  709. // release all slots
  710. for (llama_client_slot &slot : slots)
  711. {
  712. slot.release();
  713. }
  714. system_need_update = true;
  715. }
  716. void process_system_prompt_data(const json &sys_props) {
  717. system_prompt = sys_props.value("prompt", "");
  718. name_user = sys_props.value("anti_prompt", "");
  719. name_assistant = sys_props.value("assistant_name", "");
  720. notify_system_prompt_changed();
  721. }
  722. static size_t find_stopping_strings(const std::string &text, const size_t last_token_size,
  723. const stop_type type, llama_client_slot &slot)
  724. {
  725. size_t stop_pos = std::string::npos;
  726. for (const std::string &word : slot.params.antiprompt)
  727. {
  728. size_t pos;
  729. if (type == STOP_FULL)
  730. {
  731. const size_t tmp = word.size() + last_token_size;
  732. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  733. pos = text.find(word, from_pos);
  734. }
  735. else
  736. {
  737. pos = find_partial_stop_string(word, text);
  738. }
  739. if (pos != std::string::npos &&
  740. (stop_pos == std::string::npos || pos < stop_pos))
  741. {
  742. if (type == STOP_FULL)
  743. {
  744. slot.stopped_word = true;
  745. slot.stopping_word = word;
  746. slot.has_next_token = false;
  747. }
  748. stop_pos = pos;
  749. }
  750. }
  751. return stop_pos;
  752. }
  753. bool process_token(completion_token_output &result, llama_client_slot &slot) {
  754. // remember which tokens were sampled - used for repetition penalties during sampling
  755. const std::string token_str = llama_token_to_piece(ctx, result.tok);
  756. slot.sampled = result.tok;
  757. // search stop word and delete it
  758. slot.generated_text += token_str;
  759. slot.has_next_token = true;
  760. if (slot.ctx_sampling->params.use_penalty_prompt_tokens && result.tok != -1)
  761. {
  762. // we can change penalty_prompt_tokens because it is always created from scratch each request
  763. slot.ctx_sampling->params.penalty_prompt_tokens.push_back(result.tok);
  764. }
  765. // check if there is incomplete UTF-8 character at the end
  766. bool incomplete = false;
  767. for (unsigned i = 1; i < 5 && i <= slot.generated_text.size(); ++i)
  768. {
  769. unsigned char c = slot.generated_text[slot.generated_text.size() - i];
  770. if ((c & 0xC0) == 0x80)
  771. {
  772. // continuation byte: 10xxxxxx
  773. continue;
  774. }
  775. if ((c & 0xE0) == 0xC0)
  776. {
  777. // 2-byte character: 110xxxxx ...
  778. incomplete = i < 2;
  779. }
  780. else if ((c & 0xF0) == 0xE0)
  781. {
  782. // 3-byte character: 1110xxxx ...
  783. incomplete = i < 3;
  784. }
  785. else if ((c & 0xF8) == 0xF0)
  786. {
  787. // 4-byte character: 11110xxx ...
  788. incomplete = i < 4;
  789. }
  790. // else 1-byte character or invalid byte
  791. break;
  792. }
  793. if (!incomplete)
  794. {
  795. size_t pos = std::min(slot.sent_count, slot.generated_text.size());
  796. const std::string str_test = slot.generated_text.substr(pos);
  797. bool is_stop_full = false;
  798. size_t stop_pos = find_stopping_strings(str_test, token_str.size(), STOP_FULL, slot);
  799. if (stop_pos != std::string::npos)
  800. {
  801. is_stop_full = true;
  802. slot.generated_text.erase(
  803. slot.generated_text.begin() + pos + stop_pos,
  804. slot.generated_text.end());
  805. pos = std::min(slot.sent_count, slot.generated_text.size());
  806. }
  807. else
  808. {
  809. is_stop_full = false;
  810. stop_pos = find_stopping_strings(str_test, token_str.size(), STOP_PARTIAL, slot);
  811. }
  812. // check if there is any token to predict
  813. if (stop_pos == std::string::npos || (!slot.has_next_token && !is_stop_full && stop_pos > 0))
  814. {
  815. // no send the stop word in the response
  816. result.text_to_send = slot.generated_text.substr(pos, std::string::npos);
  817. slot.sent_count += result.text_to_send.size();
  818. // add the token to slot queue and cache
  819. }
  820. slot.add_token_string(result);
  821. if (slot.params.stream)
  822. {
  823. send_partial_response(slot, result);
  824. }
  825. }
  826. if (incomplete)
  827. {
  828. slot.has_next_token = true;
  829. }
  830. // check the limits
  831. if (slot.n_decoded > 0 && slot.has_next_token && !slot.has_budget(params))
  832. {
  833. slot.stopped_limit = true;
  834. slot.has_next_token = false;
  835. }
  836. if (!slot.cache_tokens.empty() && result.tok == llama_token_eos(model))
  837. {
  838. slot.stopped_eos = true;
  839. slot.has_next_token = false;
  840. LOG_VERBOSE("eos token found", {});
  841. }
  842. LOG_VERBOSE("next token", {
  843. {"token", result.tok},
  844. {"token_text", tokens_to_output_formatted_string(ctx, result.tok)},
  845. {"has_next_token", slot.has_next_token},
  846. {"n_remain", slot.n_remaining},
  847. {"num_tokens_predicted", slot.n_decoded},
  848. {"stopped_eos", slot.stopped_eos},
  849. {"stopped_word", slot.stopped_word},
  850. {"stopped_limit", slot.stopped_limit},
  851. {"stopping_word", slot.stopping_word},
  852. });
  853. return slot.has_next_token; // continue
  854. }
  855. bool process_images(llama_client_slot &slot) const
  856. {
  857. for (slot_image &img : slot.images)
  858. {
  859. if (!img.request_encode_image)
  860. {
  861. continue;
  862. }
  863. clip_image_f32_batch img_res_v;
  864. img_res_v.size = 0;
  865. img_res_v.data = nullptr;
  866. if (!clip_image_preprocess(clp_ctx, img.img_data, img_res_v))
  867. {
  868. LOG_TEE("Error processing the given image");
  869. clip_free(clp_ctx);
  870. clip_image_f32_batch_free(img_res_v);
  871. return false;
  872. }
  873. if (img_res_v.size == 0)
  874. {
  875. LOG_TEE("Error processing the given image");
  876. return false;
  877. }
  878. // note: assumes only one image was returned by clip_image_preprocess
  879. clip_image_f32 * img_res = img_res_v.data;
  880. img.image_tokens = clip_n_patches(clp_ctx);
  881. img.image_embedding = (float *)malloc(clip_embd_nbytes(clp_ctx));
  882. if (!img.image_embedding)
  883. {
  884. LOG_TEE("Unable to allocate memory for image embeddings\n");
  885. clip_image_f32_batch_free(img_res_v);
  886. clip_free(clp_ctx);
  887. return false;
  888. }
  889. LOG_TEE("slot %i - encoding image [id: %i]\n", slot.id, img.id);
  890. if (!clip_image_encode(clp_ctx, params.n_threads, img_res, img.image_embedding))
  891. {
  892. LOG_TEE("Unable to encode image\n");
  893. clip_image_f32_batch_free(img_res_v);
  894. return false;
  895. }
  896. clip_image_f32_batch_free(img_res_v);
  897. img.request_encode_image = false;
  898. }
  899. return slot.images.size() > 0;
  900. }
  901. void send_error(task_server& task, const std::string &error)
  902. {
  903. LOG_TEE("task %i - error: %s\n", task.id, error.c_str());
  904. task_result res;
  905. res.id = task.id;
  906. res.multitask_id = task.multitask_id;
  907. res.stop = false;
  908. res.error = true;
  909. res.result_json = { { "content", error } };
  910. queue_results.send(res);
  911. }
  912. json get_formated_generation(llama_client_slot &slot)
  913. {
  914. const auto eos_bias = slot.sparams.logit_bias.find(llama_token_eos(model));
  915. const bool ignore_eos = eos_bias != slot.sparams.logit_bias.end() &&
  916. eos_bias->second < 0.0f && std::isinf(eos_bias->second);
  917. std::vector<std::string> samplers_sequence;
  918. for (const auto &sampler_type : slot.sparams.samplers_sequence)
  919. {
  920. samplers_sequence.emplace_back(sampler_type_to_name_string(sampler_type));
  921. }
  922. return json {
  923. {"n_ctx", slot.n_ctx},
  924. {"n_predict", slot.n_predict},
  925. {"model", params.model_alias},
  926. {"seed", slot.params.seed},
  927. {"temperature", slot.sparams.temp},
  928. {"dynatemp_range", slot.sparams.dynatemp_range},
  929. {"dynatemp_exponent", slot.sparams.dynatemp_exponent},
  930. {"top_k", slot.sparams.top_k},
  931. {"top_p", slot.sparams.top_p},
  932. {"min_p", slot.sparams.min_p},
  933. {"tfs_z", slot.sparams.tfs_z},
  934. {"typical_p", slot.sparams.typical_p},
  935. {"repeat_last_n", slot.sparams.penalty_last_n},
  936. {"repeat_penalty", slot.sparams.penalty_repeat},
  937. {"presence_penalty", slot.sparams.penalty_present},
  938. {"frequency_penalty", slot.sparams.penalty_freq},
  939. {"penalty_prompt_tokens", slot.sparams.penalty_prompt_tokens},
  940. {"use_penalty_prompt_tokens", slot.sparams.use_penalty_prompt_tokens},
  941. {"mirostat", slot.sparams.mirostat},
  942. {"mirostat_tau", slot.sparams.mirostat_tau},
  943. {"mirostat_eta", slot.sparams.mirostat_eta},
  944. {"penalize_nl", slot.sparams.penalize_nl},
  945. {"stop", slot.params.antiprompt},
  946. {"n_predict", slot.params.n_predict},
  947. {"n_keep", params.n_keep},
  948. {"ignore_eos", ignore_eos},
  949. {"stream", slot.params.stream},
  950. {"logit_bias", slot.sparams.logit_bias},
  951. {"n_probs", slot.sparams.n_probs},
  952. {"grammar", slot.sparams.grammar},
  953. {"samplers", samplers_sequence}
  954. };
  955. }
  956. void send_partial_response(llama_client_slot &slot, completion_token_output tkn)
  957. {
  958. task_result res;
  959. res.id = slot.task_id;
  960. res.multitask_id = slot.multitask_id;
  961. res.error = false;
  962. res.stop = false;
  963. res.result_json = json
  964. {
  965. {"content", tkn.text_to_send},
  966. {"stop", false},
  967. {"slot_id", slot.id},
  968. {"multimodal", multimodal}
  969. };
  970. if (slot.sparams.n_probs > 0)
  971. {
  972. std::vector<completion_token_output> probs_output = {};
  973. const std::vector<llama_token> to_send_toks = llama_tokenize(ctx, tkn.text_to_send, false);
  974. size_t probs_pos = std::min(slot.sent_token_probs_index, slot.generated_token_probs.size());
  975. size_t probs_stop_pos = std::min(slot.sent_token_probs_index + to_send_toks.size(), slot.generated_token_probs.size());
  976. if (probs_pos < probs_stop_pos)
  977. {
  978. probs_output = std::vector<completion_token_output>(slot.generated_token_probs.begin() + probs_pos, slot.generated_token_probs.begin() + probs_stop_pos);
  979. }
  980. slot.sent_token_probs_index = probs_stop_pos;
  981. res.result_json["completion_probabilities"] = probs_vector_to_json(ctx, probs_output);
  982. }
  983. if (slot.oaicompat)
  984. {
  985. res.result_json["oaicompat_token_ctr"] = slot.n_decoded;
  986. res.result_json["model"] = slot.oaicompat_model;
  987. }
  988. queue_results.send(res);
  989. }
  990. void send_final_response(llama_client_slot &slot)
  991. {
  992. task_result res;
  993. res.id = slot.task_id;
  994. res.multitask_id = slot.multitask_id;
  995. res.error = false;
  996. res.stop = true;
  997. res.result_json = json
  998. {
  999. {"content", !slot.params.stream ? slot.generated_text : ""},
  1000. {"slot_id", slot.id},
  1001. {"stop", true},
  1002. {"model", params.model_alias},
  1003. {"tokens_predicted", slot.n_decoded},
  1004. {"tokens_evaluated", slot.num_prompt_tokens},
  1005. {"generation_settings", get_formated_generation(slot)},
  1006. {"prompt", slot.prompt},
  1007. {"truncated", slot.truncated},
  1008. {"stopped_eos", slot.stopped_eos},
  1009. {"stopped_word", slot.stopped_word},
  1010. {"stopped_limit", slot.stopped_limit},
  1011. {"stopping_word", slot.stopping_word},
  1012. {"tokens_cached", slot.n_past},
  1013. {"timings", slot.get_formated_timings()}
  1014. };
  1015. if (slot.sparams.n_probs > 0)
  1016. {
  1017. std::vector<completion_token_output> probs = {};
  1018. if (!slot.params.stream && slot.stopped_word)
  1019. {
  1020. const std::vector<llama_token> stop_word_toks = llama_tokenize(ctx, slot.stopping_word, false);
  1021. probs = std::vector<completion_token_output>(slot.generated_token_probs.begin(), slot.generated_token_probs.end() - stop_word_toks.size());
  1022. }
  1023. else
  1024. {
  1025. probs = std::vector<completion_token_output>(
  1026. slot.generated_token_probs.begin(),
  1027. slot.generated_token_probs.end());
  1028. }
  1029. res.result_json["completion_probabilities"] = probs_vector_to_json(ctx, probs);
  1030. }
  1031. if (slot.oaicompat)
  1032. {
  1033. res.result_json["oaicompat_token_ctr"] = slot.n_decoded;
  1034. res.result_json["model"] = slot.oaicompat_model;
  1035. }
  1036. queue_results.send(res);
  1037. }
  1038. void send_embedding(llama_client_slot &slot)
  1039. {
  1040. task_result res;
  1041. res.id = slot.task_id;
  1042. res.multitask_id = slot.multitask_id;
  1043. res.error = false;
  1044. res.stop = true;
  1045. const int n_embd = llama_n_embd(model);
  1046. if (!params.embedding)
  1047. {
  1048. LOG_WARNING("embedding disabled", {
  1049. {"params.embedding", params.embedding},
  1050. });
  1051. res.result_json = json
  1052. {
  1053. {"embedding", std::vector<float>(n_embd, 0.0f)},
  1054. };
  1055. }
  1056. else
  1057. {
  1058. const float *data = llama_get_embeddings(ctx);
  1059. std::vector<float> embedding(data, data + n_embd);
  1060. res.result_json = json
  1061. {
  1062. {"embedding", embedding },
  1063. };
  1064. }
  1065. queue_results.send(res);
  1066. }
  1067. void request_completion(int task_id, json data, bool infill, bool embedding, int multitask_id)
  1068. {
  1069. task_server task;
  1070. task.id = task_id;
  1071. task.target_id = 0;
  1072. task.data = std::move(data);
  1073. task.infill_mode = infill;
  1074. task.embedding_mode = embedding;
  1075. task.type = TASK_TYPE_COMPLETION;
  1076. task.multitask_id = multitask_id;
  1077. // when a completion task's prompt array is not a singleton, we split it into multiple requests
  1078. // otherwise, it's a single-prompt task, we actually queue it
  1079. // if there's numbers in the prompt array it will be treated as an array of tokens
  1080. if (task.data.count("prompt") != 0 && task.data.at("prompt").size() > 1) {
  1081. bool numbers = false;
  1082. for (const auto& e : task.data.at("prompt")) {
  1083. if (e.is_number()) {
  1084. numbers = true;
  1085. break;
  1086. }
  1087. }
  1088. // NOTE: split_multiprompt_task() does not handle a mix of strings and numbers,
  1089. // it will completely stall the server. I don't know where the bug for this is.
  1090. //
  1091. // if there are numbers, it needs to be treated like a single prompt,
  1092. // queue_tasks handles a mix of strings and numbers just fine.
  1093. if (numbers) {
  1094. queue_tasks.post(task);
  1095. } else {
  1096. split_multiprompt_task(task_id, task);
  1097. }
  1098. } else {
  1099. queue_tasks.post(task);
  1100. }
  1101. }
  1102. // for multiple images processing
  1103. bool ingest_images(llama_client_slot &slot, int n_batch)
  1104. {
  1105. int image_idx = 0;
  1106. while (image_idx < (int) slot.images.size())
  1107. {
  1108. slot_image &img = slot.images[image_idx];
  1109. // process prefix prompt
  1110. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch)
  1111. {
  1112. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  1113. llama_batch batch_view = {
  1114. n_tokens,
  1115. batch.token + i,
  1116. nullptr,
  1117. batch.pos + i,
  1118. batch.n_seq_id + i,
  1119. batch.seq_id + i,
  1120. batch.logits + i,
  1121. 0, 0, 0, // unused
  1122. };
  1123. if (llama_decode(ctx, batch_view))
  1124. {
  1125. LOG_TEE("%s : failed to eval\n", __func__);
  1126. return false;
  1127. }
  1128. }
  1129. // process image with llm
  1130. for (int i = 0; i < img.image_tokens; i += n_batch)
  1131. {
  1132. int n_eval = img.image_tokens - i;
  1133. if (n_eval > n_batch)
  1134. {
  1135. n_eval = n_batch;
  1136. }
  1137. const int n_embd = llama_n_embd(model);
  1138. llama_batch batch_img = { n_eval, nullptr, (img.image_embedding + i * n_embd), nullptr, nullptr, nullptr, nullptr, slot.n_past, 1, 0, };
  1139. if (llama_decode(ctx, batch_img))
  1140. {
  1141. LOG_TEE("%s : failed to eval image\n", __func__);
  1142. return false;
  1143. }
  1144. slot.n_past += n_eval;
  1145. }
  1146. image_idx++;
  1147. llama_batch_clear(batch);
  1148. // append prefix of next image
  1149. const auto json_prompt = (image_idx >= (int) slot.images.size()) ?
  1150. slot.params.input_suffix : // no more images, then process suffix prompt
  1151. (json)(slot.images[image_idx].prefix_prompt);
  1152. std::vector<llama_token> append_tokens = tokenize(json_prompt, false); // has next image
  1153. for (int i = 0; i < (int) append_tokens.size(); ++i)
  1154. {
  1155. llama_batch_add(batch, append_tokens[i], system_tokens.size() + slot.n_past, { slot.id }, true);
  1156. slot.n_past += 1;
  1157. }
  1158. }
  1159. return true;
  1160. }
  1161. void request_cancel(int task_id)
  1162. {
  1163. task_server task;
  1164. task.type = TASK_TYPE_CANCEL;
  1165. task.target_id = task_id;
  1166. queue_tasks.post(task);
  1167. }
  1168. void split_multiprompt_task(int multitask_id, task_server& multiprompt_task)
  1169. {
  1170. int prompt_count = multiprompt_task.data.at("prompt").size();
  1171. if (prompt_count <= 1) {
  1172. send_error(multiprompt_task, "error while handling multiple prompts");
  1173. return;
  1174. }
  1175. // generate all the ID for subtask
  1176. std::vector<int> subtask_ids(prompt_count);
  1177. for (int i = 0; i < prompt_count; i++)
  1178. {
  1179. subtask_ids[i] = queue_tasks.get_new_id();
  1180. }
  1181. // queue up the multitask so we can track its subtask progression
  1182. queue_tasks.add_multitask(multitask_id, subtask_ids);
  1183. // add subtasks
  1184. for (int i = 0; i < prompt_count; i++)
  1185. {
  1186. json subtask_data = multiprompt_task.data;
  1187. subtask_data["prompt"] = subtask_data["prompt"][i];
  1188. // subtasks inherit everything else (infill mode, embedding mode, etc.)
  1189. request_completion(subtask_ids[i], subtask_data, multiprompt_task.infill_mode, multiprompt_task.embedding_mode, multitask_id);
  1190. }
  1191. }
  1192. void process_single_task(task_server& task)
  1193. {
  1194. switch (task.type)
  1195. {
  1196. case TASK_TYPE_COMPLETION: {
  1197. llama_client_slot *slot = get_slot(json_value(task.data, "slot_id", -1));
  1198. if (slot == nullptr)
  1199. {
  1200. // if no slot is available, we defer this task for processing later
  1201. LOG_VERBOSE("no slot is available", {});
  1202. queue_tasks.defer(task);
  1203. break;
  1204. }
  1205. if (task.data.contains("system_prompt"))
  1206. {
  1207. if (!all_slots_are_idle) {
  1208. send_error(task, "system prompt can only be updated when all slots are idle");
  1209. break;
  1210. }
  1211. process_system_prompt_data(task.data["system_prompt"]);
  1212. // reset cache_tokens for all slots
  1213. for (llama_client_slot &slot : slots)
  1214. {
  1215. slot.cache_tokens.clear();
  1216. slot.n_past = 0;
  1217. slot.n_past_se = 0;
  1218. }
  1219. }
  1220. slot->reset();
  1221. slot->infill = task.infill_mode;
  1222. slot->embedding = task.embedding_mode;
  1223. slot->task_id = task.id;
  1224. slot->multitask_id = task.multitask_id;
  1225. if (!launch_slot_with_data(slot, task.data))
  1226. {
  1227. // send error result
  1228. send_error(task, "internal_error");
  1229. break;
  1230. }
  1231. } break;
  1232. case TASK_TYPE_CANCEL: { // release slot linked with the task id
  1233. for (auto & slot : slots)
  1234. {
  1235. if (slot.task_id == task.target_id)
  1236. {
  1237. slot.release();
  1238. break;
  1239. }
  1240. }
  1241. } break;
  1242. case TASK_TYPE_NEXT_RESPONSE: {
  1243. // do nothing
  1244. } break;
  1245. }
  1246. }
  1247. void on_finish_multitask(task_multi& multitask)
  1248. {
  1249. // all subtasks done == multitask is done
  1250. task_result result;
  1251. result.id = multitask.id;
  1252. result.stop = true;
  1253. result.error = false;
  1254. // collect json results into one json result
  1255. std::vector<json> result_jsons;
  1256. for (auto& subres : multitask.results)
  1257. {
  1258. result_jsons.push_back(subres.result_json);
  1259. result.error = result.error && subres.error;
  1260. }
  1261. result.result_json = json{ { "results", result_jsons } };
  1262. queue_results.send(result);
  1263. }
  1264. bool update_slots() {
  1265. if (system_need_update)
  1266. {
  1267. LOG_TEE("updating system prompt\n");
  1268. update_system_prompt();
  1269. }
  1270. llama_batch_clear(batch);
  1271. if (all_slots_are_idle)
  1272. {
  1273. if (system_prompt.empty() && clean_kv_cache)
  1274. {
  1275. LOG_TEE("all slots are idle and system prompt is empty, clear the KV cache\n");
  1276. kv_cache_clear();
  1277. }
  1278. return true;
  1279. }
  1280. task_server task;
  1281. task.type = TASK_TYPE_NEXT_RESPONSE;
  1282. task.target_id = -1;
  1283. queue_tasks.post(task);
  1284. for (llama_client_slot &slot : slots)
  1285. {
  1286. if (slot.ga_n == 1)
  1287. {
  1288. if (slot.is_processing() && system_tokens.size() + slot.cache_tokens.size() >= (size_t) slot.n_ctx)
  1289. {
  1290. // Shift context
  1291. const int n_left = system_tokens.size() + slot.n_past - slot.params.n_keep - 1;
  1292. const int n_discard = n_left / 2;
  1293. LOG_TEE("slot %d: context shift - n_keep = %d, n_left = %d, n_discard = %d\n", slot.id, slot.params.n_keep, n_left, n_discard);
  1294. llama_kv_cache_seq_rm (ctx, slot.id, slot.params.n_keep + 1 , slot.params.n_keep + n_discard + 1);
  1295. llama_kv_cache_seq_shift(ctx, slot.id, slot.params.n_keep + 1 + n_discard, system_tokens.size() + slot.n_past, -n_discard);
  1296. for (size_t i = slot.params.n_keep + 1 + n_discard; i < slot.cache_tokens.size(); i++)
  1297. {
  1298. slot.cache_tokens[i - n_discard] = slot.cache_tokens[i];
  1299. }
  1300. slot.cache_tokens.resize(slot.cache_tokens.size() - n_discard);
  1301. slot.n_past -= n_discard;
  1302. slot.truncated = true;
  1303. LOG_VERBOSE("context shift", {
  1304. { "n_ctx", n_ctx },
  1305. { "n_keep", params.n_keep },
  1306. { "n_left", n_left },
  1307. });
  1308. }
  1309. }
  1310. }
  1311. // decode any currently ongoing sequences
  1312. for (auto & slot : slots)
  1313. {
  1314. // release the slot
  1315. if (slot.command == RELEASE)
  1316. {
  1317. slot.state = IDLE;
  1318. slot.command = NONE;
  1319. slot.t_last_used = ggml_time_us();
  1320. LOG_TEE("slot %d released (%d tokens in cache)\n", slot.id, (int) slot.cache_tokens.size());
  1321. queue_tasks.notify_slot_changed();
  1322. continue;
  1323. }
  1324. if (slot.state == IDLE)
  1325. {
  1326. continue;
  1327. }
  1328. slot.i_batch = batch.n_tokens;
  1329. const int32_t slot_npast = slot.n_past_se > 0 ? slot.n_past_se : slot.n_past;
  1330. // TODO: we always have to take into account the "system_tokens"
  1331. // this is not great and needs to be improved somehow
  1332. llama_batch_add(batch, slot.sampled, system_tokens.size() + slot_npast, { slot.id }, true);
  1333. slot.n_past += 1;
  1334. }
  1335. // process in chunks of params.n_batch
  1336. int32_t n_batch = params.n_batch;
  1337. // assign workload to the slots
  1338. if (params.cont_batching || batch.n_tokens == 0)
  1339. {
  1340. for (auto & slot : slots)
  1341. {
  1342. const bool has_prompt = slot.prompt.is_array() || (slot.prompt.is_string() && !slot.prompt.get<std::string>().empty()) || !slot.images.empty();
  1343. // empty prompt passed -> release the slot and send empty response
  1344. // note: infill mode allows empty prompt
  1345. if (slot.state == IDLE && slot.command == LOAD_PROMPT && !has_prompt && !slot.infill)
  1346. {
  1347. slot.release();
  1348. slot.print_timings();
  1349. send_final_response(slot);
  1350. continue;
  1351. }
  1352. // need process the prompt
  1353. if (slot.state == IDLE && slot.command == LOAD_PROMPT)
  1354. {
  1355. slot.state = PROCESSING;
  1356. slot.command = NONE;
  1357. std::vector<llama_token> prompt_tokens;
  1358. slot.t_start_process_prompt = ggml_time_us();
  1359. slot.t_start_genereration = 0;
  1360. if (slot.infill)
  1361. {
  1362. bool suff_rm_leading_spc = true;
  1363. if (params.input_suffix.find_first_of(' ') == 0 && params.input_suffix.size() > 1)
  1364. {
  1365. params.input_suffix.erase(0, 1);
  1366. suff_rm_leading_spc = false;
  1367. }
  1368. auto prefix_tokens = tokenize(slot.params.input_prefix, false);
  1369. auto suffix_tokens = tokenize(slot.params.input_suffix, false);
  1370. const int space_token = 29871; // TODO: this should not be hardcoded
  1371. if (suff_rm_leading_spc && !suffix_tokens.empty() && suffix_tokens[0] == space_token) {
  1372. suffix_tokens.erase(suffix_tokens.begin());
  1373. }
  1374. prefix_tokens.insert(prefix_tokens.begin(), llama_token_prefix(model));
  1375. prefix_tokens.insert(prefix_tokens.begin(), llama_token_bos(model)); // always add BOS
  1376. prefix_tokens.insert(prefix_tokens.end(), llama_token_suffix(model));
  1377. prefix_tokens.insert(prefix_tokens.end(), suffix_tokens.begin(), suffix_tokens.end());
  1378. prefix_tokens.push_back(llama_token_middle(model));
  1379. prompt_tokens = prefix_tokens;
  1380. }
  1381. else
  1382. {
  1383. prompt_tokens = tokenize(slot.prompt, system_prompt.empty() && add_bos_token); // add BOS if there isn't system prompt
  1384. }
  1385. slot.num_prompt_tokens = prompt_tokens.size();
  1386. if (slot.params.n_keep < 0)
  1387. {
  1388. slot.params.n_keep = slot.num_prompt_tokens;
  1389. }
  1390. slot.params.n_keep = std::min(slot.n_ctx - 4, slot.params.n_keep);
  1391. // if input prompt is too big, truncate it
  1392. if (slot.num_prompt_tokens >= slot.n_ctx)
  1393. {
  1394. const int n_left = slot.n_ctx - slot.params.n_keep;
  1395. const int n_block_size = n_left / 2;
  1396. const int erased_blocks = (slot.num_prompt_tokens - slot.params.n_keep - n_block_size) / n_block_size;
  1397. std::vector<llama_token> new_tokens(prompt_tokens.begin(), prompt_tokens.begin() + slot.params.n_keep);
  1398. new_tokens.insert(new_tokens.end(), prompt_tokens.begin() + slot.params.n_keep + erased_blocks * n_block_size, prompt_tokens.end());
  1399. LOG_VERBOSE("input truncated", {
  1400. {"n_ctx", slot.n_ctx},
  1401. {"n_keep", slot.params.n_keep},
  1402. {"n_left", n_left},
  1403. {"new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend())},
  1404. });
  1405. slot.truncated = true;
  1406. prompt_tokens = new_tokens;
  1407. slot.num_prompt_tokens = prompt_tokens.size();
  1408. GGML_ASSERT(slot.num_prompt_tokens < slot.n_ctx);
  1409. }
  1410. if (!slot.params.cache_prompt)
  1411. {
  1412. llama_sampling_reset(slot.ctx_sampling);
  1413. slot.n_past = 0;
  1414. slot.n_past_se = 0;
  1415. slot.ga_i = 0;
  1416. slot.num_prompt_tokens_processed = slot.num_prompt_tokens;
  1417. }
  1418. else
  1419. {
  1420. // push the prompt into the sampling context (do not apply grammar)
  1421. for (auto &token : prompt_tokens)
  1422. {
  1423. llama_sampling_accept(slot.ctx_sampling, ctx, token, false);
  1424. }
  1425. slot.n_past = common_part(slot.cache_tokens, prompt_tokens);
  1426. slot.num_prompt_tokens_processed = slot.num_prompt_tokens - slot.n_past;
  1427. if (slot.ga_n != 1)
  1428. {
  1429. int ga_i = 0;
  1430. int32_t ga_n = slot.ga_n;
  1431. int32_t ga_w = slot.ga_w;
  1432. int32_t slot_npast = 0;
  1433. for (int k = 0; k < slot.n_past; ++k)
  1434. {
  1435. while (slot_npast >= ga_i + ga_w) {
  1436. const int bd = (ga_w/ga_n)*(ga_n - 1);
  1437. slot_npast -= bd;
  1438. ga_i += ga_w/ga_n;
  1439. }
  1440. slot_npast++;
  1441. }
  1442. slot.n_past_se = slot_npast;
  1443. slot.ga_i = ga_i;
  1444. }
  1445. LOG_TEE("slot %d : in cache: %i tokens | to process: %i tokens\n", slot.id, slot.n_past, slot.num_prompt_tokens_processed);
  1446. }
  1447. slot.cache_tokens = prompt_tokens;
  1448. if (slot.n_past == slot.num_prompt_tokens && slot.n_past > 0)
  1449. {
  1450. // we have to evaluate at least 1 token to generate logits.
  1451. LOG_TEE("slot %d : we have to evaluate at least 1 token to generate logits\n", slot.id);
  1452. slot.n_past--;
  1453. if (slot.ga_i > 0)
  1454. {
  1455. slot.n_past_se--;
  1456. }
  1457. }
  1458. LOG_TEE("slot %d : kv cache rm - [%d, end)\n", slot.id, (int) system_tokens.size() + slot.n_past);
  1459. llama_kv_cache_seq_rm(ctx, slot.id, system_tokens.size() + slot.n_past, -1);
  1460. LOG_VERBOSE("prompt ingested", {
  1461. {"n_past", slot.n_past},
  1462. {"cached", tokens_to_str(ctx, slot.cache_tokens.cbegin(), slot.cache_tokens.cbegin() + slot.n_past)},
  1463. {"to_eval", tokens_to_str(ctx, slot.cache_tokens.cbegin() + slot.n_past, slot.cache_tokens.cend())},
  1464. });
  1465. const bool has_images = process_images(slot);
  1466. // process the prefix of first image
  1467. std::vector<llama_token> prefix_tokens = has_images ? tokenize(slot.images[0].prefix_prompt, add_bos_token) : prompt_tokens;
  1468. int32_t slot_npast = slot.n_past_se > 0 ? slot.n_past_se : slot.n_past;
  1469. int32_t ga_i = slot.ga_i;
  1470. int32_t ga_n = slot.ga_n;
  1471. int32_t ga_w = slot.ga_w;
  1472. for (; slot.n_past < (int) prefix_tokens.size(); ++slot.n_past)
  1473. {
  1474. if (slot.ga_n != 1)
  1475. {
  1476. while (slot_npast >= ga_i + ga_w) {
  1477. const int bd = (ga_w/ga_n)*(ga_n - 1);
  1478. slot_npast -= bd;
  1479. ga_i += ga_w/ga_n;
  1480. }
  1481. }
  1482. llama_batch_add(batch, prefix_tokens[slot.n_past], system_tokens.size() + slot_npast, {slot.id }, false);
  1483. slot_npast++;
  1484. }
  1485. if (has_images && !ingest_images(slot, n_batch))
  1486. {
  1487. LOG_TEE("failed processing images\n");
  1488. return false;
  1489. }
  1490. // extract the logits only for the last token
  1491. if (batch.n_tokens > 0)
  1492. {
  1493. batch.logits[batch.n_tokens - 1] = true;
  1494. }
  1495. slot.n_decoded = 0;
  1496. slot.i_batch = batch.n_tokens - 1;
  1497. }
  1498. }
  1499. }
  1500. if (batch.n_tokens == 0)
  1501. {
  1502. all_slots_are_idle = true;
  1503. return true;
  1504. }
  1505. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch)
  1506. {
  1507. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  1508. for (auto & slot : slots)
  1509. {
  1510. if (slot.ga_n != 1)
  1511. {
  1512. // context extension via Self-Extend
  1513. while (slot.n_past_se >= slot.ga_i + slot.ga_w)
  1514. {
  1515. const int ib = (slot.ga_n * slot.ga_i) / slot.ga_w;
  1516. const int bd = (slot.ga_w / slot.ga_n) * (slot.ga_n - 1);
  1517. const int dd = (slot.ga_w / slot.ga_n) - ib * bd - slot.ga_w;
  1518. LOG_TEE("\n");
  1519. LOG_TEE("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", slot.ga_i, slot.n_past_se, ib * bd, slot.ga_i + ib * bd, slot.n_past_se + ib * bd);
  1520. LOG_TEE("div: [%6d, %6d] / %6d -> [%6d, %6d]\n", slot.ga_i + ib * bd, slot.ga_i + ib * bd + slot.ga_w, slot.ga_n, (slot.ga_i + ib * bd) / slot.ga_n, (slot.ga_i + ib * bd + slot.ga_w) / slot.ga_n);
  1521. LOG_TEE("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", slot.ga_i + ib * bd + slot.ga_w, slot.n_past_se + ib * bd, dd, slot.ga_i + ib * bd + slot.ga_w + dd, slot.n_past_se + ib * bd + dd);
  1522. llama_kv_cache_seq_shift(ctx, slot.id, slot.ga_i, slot.n_past_se, ib * bd);
  1523. llama_kv_cache_seq_div(ctx, slot.id, slot.ga_i + ib * bd, slot.ga_i + ib * bd + slot.ga_w,slot.ga_n);
  1524. llama_kv_cache_seq_shift(ctx, slot.id, slot.ga_i + ib * bd + slot.ga_w,slot.n_past_se + ib * bd, dd);
  1525. slot.n_past_se -= bd;
  1526. slot.ga_i += slot.ga_w / slot.ga_n;
  1527. LOG_TEE("\nn_past_old = %d, n_past = %d, ga_i = %d\n\n", slot.n_past_se + bd, slot.n_past_se, slot.ga_i);
  1528. }
  1529. slot.n_past_se += n_tokens;
  1530. }
  1531. }
  1532. llama_batch batch_view =
  1533. {
  1534. n_tokens,
  1535. batch.token + i,
  1536. nullptr,
  1537. batch.pos + i,
  1538. batch.n_seq_id + i,
  1539. batch.seq_id + i,
  1540. batch.logits + i,
  1541. 0, 0, 0, // unused
  1542. };
  1543. const int ret = llama_decode(ctx, batch_view);
  1544. if (ret != 0)
  1545. {
  1546. if (n_batch == 1 || ret < 0)
  1547. {
  1548. // if you get here, it means the KV cache is full - try increasing it via the context size
  1549. LOG_TEE("%s : failed to decode the batch, n_batch = %d, ret = %d\n", __func__, n_batch, ret);
  1550. return false;
  1551. }
  1552. LOG_TEE("%s : failed to find free space in the KV cache, retrying with smaller n_batch = %d\n", __func__, n_batch / 2);
  1553. // retry with half the batch size to try to find a free slot in the KV cache
  1554. n_batch /= 2;
  1555. i -= n_batch;
  1556. continue;
  1557. }
  1558. for (auto & slot : slots)
  1559. {
  1560. if (slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens))
  1561. {
  1562. continue;
  1563. }
  1564. // prompt evaluated for embedding
  1565. if (slot.embedding)
  1566. {
  1567. send_embedding(slot);
  1568. slot.release();
  1569. slot.i_batch = -1;
  1570. return true;
  1571. }
  1572. completion_token_output result;
  1573. const llama_token id = llama_sampling_sample(slot.ctx_sampling, ctx, NULL, slot.i_batch - i);
  1574. llama_sampling_accept(slot.ctx_sampling, ctx, id, true);
  1575. slot.n_decoded += 1;
  1576. if (slot.n_decoded == 1)
  1577. {
  1578. slot.t_start_genereration = ggml_time_us();
  1579. slot.t_prompt_processing = (slot.t_start_genereration - slot.t_start_process_prompt) / 1e3;
  1580. }
  1581. llama_token_data_array cur_p = { slot.ctx_sampling->cur.data(), slot.ctx_sampling->cur.size(), false };
  1582. result.tok = id;
  1583. const int32_t n_probs = slot.sparams.n_probs;
  1584. if (slot.sparams.temp <= 0 && n_probs > 0)
  1585. {
  1586. // for llama_sample_token_greedy we need to sort candidates
  1587. llama_sample_softmax(ctx, &cur_p);
  1588. }
  1589. for (size_t i = 0; i < std::min(cur_p.size, (size_t)n_probs); ++i)
  1590. {
  1591. result.probs.push_back({cur_p.data[i].id, cur_p.data[i].p});
  1592. }
  1593. if (!process_token(result, slot))
  1594. {
  1595. slot.release();
  1596. slot.print_timings();
  1597. send_final_response(slot);
  1598. }
  1599. slot.i_batch = -1;
  1600. }
  1601. }
  1602. return true;
  1603. }
  1604. void run_on_all_tasks_finished() {
  1605. update_slots();
  1606. }
  1607. };
  1608. static void server_print_usage(const char *argv0, const gpt_params &params,
  1609. const server_params &sparams)
  1610. {
  1611. printf("usage: %s [options]\n", argv0);
  1612. printf("\n");
  1613. printf("options:\n");
  1614. printf(" -h, --help show this help message and exit\n");
  1615. printf(" -v, --verbose verbose output (default: %s)\n", server_verbose ? "enabled" : "disabled");
  1616. printf(" -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  1617. printf(" -tb N, --threads-batch N number of threads to use during batch and prompt processing (default: same as --threads)\n");
  1618. printf(" -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  1619. printf(" --rope-scaling {none,linear,yarn}\n");
  1620. printf(" RoPE frequency scaling method, defaults to linear unless specified by the model\n");
  1621. printf(" --rope-freq-base N RoPE base frequency (default: loaded from model)\n");
  1622. printf(" --rope-freq-scale N RoPE frequency scaling factor, expands context by a factor of 1/N\n");
  1623. printf(" --yarn-ext-factor N YaRN: extrapolation mix factor (default: 1.0, 0.0 = full interpolation)\n");
  1624. printf(" --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)\n");
  1625. printf(" --yarn-beta-slow N YaRN: high correction dim or alpha (default: %.1f)\n", params.yarn_beta_slow);
  1626. printf(" --yarn-beta-fast N YaRN: low correction dim or beta (default: %.1f)\n", params.yarn_beta_fast);
  1627. printf(" -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  1628. printf(" --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  1629. printf(" not recommended: doubles context memory required and no measurable increase in quality\n");
  1630. if (llama_supports_mlock())
  1631. {
  1632. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  1633. }
  1634. if (llama_supports_mmap())
  1635. {
  1636. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  1637. }
  1638. printf(" --numa TYPE attempt optimizations that help on some NUMA systems\n");
  1639. printf(" - distribute: spread execution evenly over all nodes\n");
  1640. printf(" - isolate: only spawn threads on CPUs on the node that execution started on\n");
  1641. printf(" - numactl: use the CPU map provided my numactl\n");
  1642. if (llama_supports_gpu_offload()) {
  1643. printf(" -ngl N, --n-gpu-layers N\n");
  1644. printf(" number of layers to store in VRAM\n");
  1645. printf(" -sm SPLIT_MODE, --split-mode SPLIT_MODE\n");
  1646. printf(" how to split the model across multiple GPUs, one of:\n");
  1647. printf(" - none: use one GPU only\n");
  1648. printf(" - layer (default): split layers and KV across GPUs\n");
  1649. printf(" - row: split rows across GPUs\n");
  1650. printf(" -ts SPLIT --tensor-split SPLIT\n");
  1651. printf(" fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1\n");
  1652. printf(" -mg i, --main-gpu i the GPU to use for the model (with split-mode = none),\n");
  1653. printf(" or for intermediate results and KV (with split-mode = row)\n");
  1654. }
  1655. printf(" -m FNAME, --model FNAME\n");
  1656. printf(" model path (default: %s)\n", params.model.c_str());
  1657. printf(" -a ALIAS, --alias ALIAS\n");
  1658. printf(" set an alias for the model, will be added as `model` field in completion response\n");
  1659. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  1660. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  1661. printf(" --host ip address to listen (default (default: %s)\n", sparams.hostname.c_str());
  1662. printf(" --port PORT port to listen (default (default: %d)\n", sparams.port);
  1663. printf(" --path PUBLIC_PATH path from which to serve static files (default %s)\n", sparams.public_path.c_str());
  1664. printf(" --api-key API_KEY optional api key to enhance server security. If set, requests must include this key for access.\n");
  1665. printf(" --api-key-file FNAME path to file containing api keys delimited by new lines. If set, requests must include one of the keys for access.\n");
  1666. printf(" -to N, --timeout N server read/write timeout in seconds (default: %d)\n", sparams.read_timeout);
  1667. printf(" --embedding enable embedding vector output (default: %s)\n", params.embedding ? "enabled" : "disabled");
  1668. printf(" -np N, --parallel N number of slots for process requests (default: %d)\n", params.n_parallel);
  1669. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)\n");
  1670. printf(" -spf FNAME, --system-prompt-file FNAME\n");
  1671. printf(" set a file to load a system prompt (initial prompt of all slots), this is useful for chat applications.\n");
  1672. printf(" --mmproj MMPROJ_FILE path to a multimodal projector file for LLaVA.\n");
  1673. printf(" --log-disable disables logging to a file.\n");
  1674. printf(" --slots-endpoint-disable disables slots monitoring endpoint.\n");
  1675. printf("\n");
  1676. printf(" -n, --n-predict maximum tokens to predict (default: %d)\n", params.n_predict);
  1677. printf(" --override-kv KEY=TYPE:VALUE\n");
  1678. printf(" advanced option to override model metadata by key. may be specified multiple times.\n");
  1679. printf(" types: int, float, bool. example: --override-kv tokenizer.ggml.add_bos_token=bool:false\n");
  1680. printf(" -gan N, --grp-attn-n N set the group attention factor to extend context size through self-extend(default: 1=disabled), used together with group attention width `--grp-attn-w`");
  1681. printf(" -gaw N, --grp-attn-w N set the group attention width to extend context size through self-extend(default: 512), used together with group attention factor `--grp-attn-n`");
  1682. printf(" --chat-template FORMAT_NAME");
  1683. printf(" set chat template, possible value is: llama2, chatml (default %s)", sparams.chat_template.c_str());
  1684. printf("\n");
  1685. }
  1686. static void server_params_parse(int argc, char **argv, server_params &sparams,
  1687. gpt_params &params, llama_server_context& llama)
  1688. {
  1689. gpt_params default_params;
  1690. server_params default_sparams;
  1691. std::string arg;
  1692. bool invalid_param = false;
  1693. for (int i = 1; i < argc; i++)
  1694. {
  1695. arg = argv[i];
  1696. if (arg == "--port")
  1697. {
  1698. if (++i >= argc)
  1699. {
  1700. invalid_param = true;
  1701. break;
  1702. }
  1703. sparams.port = std::stoi(argv[i]);
  1704. }
  1705. else if (arg == "--host")
  1706. {
  1707. if (++i >= argc)
  1708. {
  1709. invalid_param = true;
  1710. break;
  1711. }
  1712. sparams.hostname = argv[i];
  1713. }
  1714. else if (arg == "--path")
  1715. {
  1716. if (++i >= argc)
  1717. {
  1718. invalid_param = true;
  1719. break;
  1720. }
  1721. sparams.public_path = argv[i];
  1722. }
  1723. else if (arg == "--api-key")
  1724. {
  1725. if (++i >= argc)
  1726. {
  1727. invalid_param = true;
  1728. break;
  1729. }
  1730. sparams.api_keys.emplace_back(argv[i]);
  1731. }
  1732. else if (arg == "--api-key-file")
  1733. {
  1734. if (++i >= argc)
  1735. {
  1736. invalid_param = true;
  1737. break;
  1738. }
  1739. std::ifstream key_file(argv[i]);
  1740. if (!key_file) {
  1741. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1742. invalid_param = true;
  1743. break;
  1744. }
  1745. std::string key;
  1746. while (std::getline(key_file, key)) {
  1747. if (key.size() > 0) {
  1748. sparams.api_keys.push_back(key);
  1749. }
  1750. }
  1751. key_file.close();
  1752. }
  1753. else if (arg == "--timeout" || arg == "-to")
  1754. {
  1755. if (++i >= argc)
  1756. {
  1757. invalid_param = true;
  1758. break;
  1759. }
  1760. sparams.read_timeout = std::stoi(argv[i]);
  1761. sparams.write_timeout = std::stoi(argv[i]);
  1762. }
  1763. else if (arg == "-m" || arg == "--model")
  1764. {
  1765. if (++i >= argc)
  1766. {
  1767. invalid_param = true;
  1768. break;
  1769. }
  1770. params.model = argv[i];
  1771. }
  1772. else if (arg == "-a" || arg == "--alias")
  1773. {
  1774. if (++i >= argc)
  1775. {
  1776. invalid_param = true;
  1777. break;
  1778. }
  1779. params.model_alias = argv[i];
  1780. }
  1781. else if (arg == "-h" || arg == "--help")
  1782. {
  1783. server_print_usage(argv[0], default_params, default_sparams);
  1784. exit(0);
  1785. }
  1786. else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size")
  1787. {
  1788. if (++i >= argc)
  1789. {
  1790. invalid_param = true;
  1791. break;
  1792. }
  1793. params.n_ctx = std::stoi(argv[i]);
  1794. }
  1795. else if (arg == "--rope-scaling")
  1796. {
  1797. if (++i >= argc)
  1798. {
  1799. invalid_param = true;
  1800. break;
  1801. }
  1802. std::string value(argv[i]);
  1803. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_NONE; }
  1804. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_LINEAR; }
  1805. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_YARN; }
  1806. else { invalid_param = true; break; }
  1807. }
  1808. else if (arg == "--rope-freq-base")
  1809. {
  1810. if (++i >= argc)
  1811. {
  1812. invalid_param = true;
  1813. break;
  1814. }
  1815. params.rope_freq_base = std::stof(argv[i]);
  1816. }
  1817. else if (arg == "--rope-freq-scale")
  1818. {
  1819. if (++i >= argc)
  1820. {
  1821. invalid_param = true;
  1822. break;
  1823. }
  1824. params.rope_freq_scale = std::stof(argv[i]);
  1825. }
  1826. else if (arg == "--yarn-ext-factor")
  1827. {
  1828. if (++i >= argc) {
  1829. invalid_param = true;
  1830. break;
  1831. }
  1832. params.yarn_ext_factor = std::stof(argv[i]);
  1833. }
  1834. else if (arg == "--yarn-attn-factor")
  1835. {
  1836. if (++i >= argc) {
  1837. invalid_param = true;
  1838. break;
  1839. }
  1840. params.yarn_attn_factor = std::stof(argv[i]);
  1841. }
  1842. else if (arg == "--yarn-beta-fast")
  1843. {
  1844. if (++i >= argc) {
  1845. invalid_param = true;
  1846. break;
  1847. }
  1848. params.yarn_beta_fast = std::stof(argv[i]);
  1849. }
  1850. else if (arg == "--yarn-beta-slow")
  1851. {
  1852. if (++i >= argc) {
  1853. invalid_param = true;
  1854. break;
  1855. }
  1856. params.yarn_beta_slow = std::stof(argv[i]);
  1857. }
  1858. else if (arg == "--threads" || arg == "-t")
  1859. {
  1860. if (++i >= argc)
  1861. {
  1862. invalid_param = true;
  1863. break;
  1864. }
  1865. params.n_threads = std::stoi(argv[i]);
  1866. }
  1867. else if (arg == "--grp-attn-n" || arg == "-gan")
  1868. {
  1869. if (++i >= argc) {
  1870. invalid_param = true;
  1871. break;
  1872. }
  1873. params.grp_attn_n = std::stoi(argv[i]);
  1874. }
  1875. else if (arg == "--grp-attn-w" || arg == "-gaw")
  1876. {
  1877. if (++i >= argc)
  1878. {
  1879. invalid_param = true;
  1880. break;
  1881. }
  1882. params.grp_attn_w = std::stoi(argv[i]);
  1883. }
  1884. else if (arg == "--threads-batch" || arg == "-tb")
  1885. {
  1886. if (++i >= argc)
  1887. {
  1888. invalid_param = true;
  1889. break;
  1890. }
  1891. params.n_threads_batch = std::stoi(argv[i]);
  1892. }
  1893. else if (arg == "-b" || arg == "--batch-size")
  1894. {
  1895. if (++i >= argc)
  1896. {
  1897. invalid_param = true;
  1898. break;
  1899. }
  1900. params.n_batch = std::stoi(argv[i]);
  1901. params.n_batch = std::min(512, params.n_batch);
  1902. }
  1903. else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers")
  1904. {
  1905. if (++i >= argc)
  1906. {
  1907. invalid_param = true;
  1908. break;
  1909. }
  1910. if (llama_supports_gpu_offload()) {
  1911. params.n_gpu_layers = std::stoi(argv[i]);
  1912. } else {
  1913. LOG_WARNING("Not compiled with GPU offload support, --n-gpu-layers option will be ignored. "
  1914. "See main README.md for information on enabling GPU BLAS support",
  1915. {{"n_gpu_layers", params.n_gpu_layers}});
  1916. }
  1917. }
  1918. else if (arg == "--split-mode" || arg == "-sm")
  1919. {
  1920. if (++i >= argc) {
  1921. invalid_param = true;
  1922. break;
  1923. }
  1924. std::string arg_next = argv[i];
  1925. if (arg_next == "none")
  1926. {
  1927. params.split_mode = LLAMA_SPLIT_NONE;
  1928. }
  1929. else if (arg_next == "layer")
  1930. {
  1931. params.split_mode = LLAMA_SPLIT_LAYER;
  1932. }
  1933. else if (arg_next == "row")
  1934. {
  1935. params.split_mode = LLAMA_SPLIT_ROW;
  1936. }
  1937. else {
  1938. invalid_param = true;
  1939. break;
  1940. }
  1941. #ifndef GGML_USE_CUBLAS
  1942. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. Setting the split mode has no effect.\n");
  1943. #endif // GGML_USE_CUBLAS
  1944. }
  1945. else if (arg == "--tensor-split" || arg == "-ts")
  1946. {
  1947. if (++i >= argc)
  1948. {
  1949. invalid_param = true;
  1950. break;
  1951. }
  1952. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL)
  1953. std::string arg_next = argv[i];
  1954. // split string by , and /
  1955. const std::regex regex{R"([,/]+)"};
  1956. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  1957. std::vector<std::string> split_arg{it, {}};
  1958. GGML_ASSERT(split_arg.size() <= llama_max_devices());
  1959. for (size_t i_device = 0; i_device < llama_max_devices(); ++i_device)
  1960. {
  1961. if (i_device < split_arg.size())
  1962. {
  1963. params.tensor_split[i_device] = std::stof(split_arg[i_device]);
  1964. }
  1965. else
  1966. {
  1967. params.tensor_split[i_device] = 0.0f;
  1968. }
  1969. }
  1970. #else
  1971. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n", {});
  1972. #endif // GGML_USE_CUBLAS
  1973. }
  1974. else if (arg == "--no-mul-mat-q" || arg == "-nommq")
  1975. {
  1976. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL)
  1977. params.mul_mat_q = false;
  1978. #else
  1979. LOG_WARNING("warning: llama.cpp was compiled without cuBLAS. Disabling mul_mat_q kernels has no effect.\n", {});
  1980. #endif // GGML_USE_CUBLAS
  1981. }
  1982. else if (arg == "--main-gpu" || arg == "-mg")
  1983. {
  1984. if (++i >= argc)
  1985. {
  1986. invalid_param = true;
  1987. break;
  1988. }
  1989. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL)
  1990. params.main_gpu = std::stoi(argv[i]);
  1991. #else
  1992. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.", {});
  1993. #endif
  1994. }
  1995. else if (arg == "--lora")
  1996. {
  1997. if (++i >= argc)
  1998. {
  1999. invalid_param = true;
  2000. break;
  2001. }
  2002. params.lora_adapter.emplace_back(argv[i], 1.0f);
  2003. params.use_mmap = false;
  2004. }
  2005. else if (arg == "--lora-scaled")
  2006. {
  2007. if (++i >= argc)
  2008. {
  2009. invalid_param = true;
  2010. break;
  2011. }
  2012. const char * lora_adapter = argv[i];
  2013. if (++i >= argc)
  2014. {
  2015. invalid_param = true;
  2016. break;
  2017. }
  2018. params.lora_adapter.emplace_back(lora_adapter, std::stof(argv[i]));
  2019. params.use_mmap = false;
  2020. }
  2021. else if (arg == "--lora-base")
  2022. {
  2023. if (++i >= argc)
  2024. {
  2025. invalid_param = true;
  2026. break;
  2027. }
  2028. params.lora_base = argv[i];
  2029. }
  2030. else if (arg == "-v" || arg == "--verbose")
  2031. {
  2032. #if SERVER_VERBOSE != 1
  2033. LOG_WARNING("server.cpp is not built with verbose logging.", {});
  2034. #else
  2035. server_verbose = true;
  2036. #endif
  2037. }
  2038. else if (arg == "--mlock")
  2039. {
  2040. params.use_mlock = true;
  2041. }
  2042. else if (arg == "--no-mmap")
  2043. {
  2044. params.use_mmap = false;
  2045. }
  2046. else if (arg == "--numa") {
  2047. if (++i >= argc) {
  2048. invalid_param = true;
  2049. break;
  2050. } else {
  2051. std::string value(argv[i]);
  2052. /**/ if (value == "distribute" || value == "" ) { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
  2053. else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
  2054. else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
  2055. else { invalid_param = true; break; }
  2056. }
  2057. }
  2058. else if (arg == "--embedding")
  2059. {
  2060. params.embedding = true;
  2061. }
  2062. else if (arg == "-cb" || arg == "--cont-batching")
  2063. {
  2064. params.cont_batching = true;
  2065. }
  2066. else if (arg == "-np" || arg == "--parallel")
  2067. {
  2068. if (++i >= argc)
  2069. {
  2070. invalid_param = true;
  2071. break;
  2072. }
  2073. params.n_parallel = std::stoi(argv[i]);
  2074. } else if (arg == "-n" || arg == "--n-predict")
  2075. {
  2076. if (++i >= argc)
  2077. {
  2078. invalid_param = true;
  2079. break;
  2080. }
  2081. params.n_predict = std::stoi(argv[i]);
  2082. } else if (arg == "-spf" || arg == "--system-prompt-file")
  2083. {
  2084. if (++i >= argc)
  2085. {
  2086. invalid_param = true;
  2087. break;
  2088. }
  2089. std::ifstream file(argv[i]);
  2090. if (!file) {
  2091. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  2092. invalid_param = true;
  2093. break;
  2094. }
  2095. std::string systm_content;
  2096. std::copy(
  2097. std::istreambuf_iterator<char>(file),
  2098. std::istreambuf_iterator<char>(),
  2099. std::back_inserter(systm_content)
  2100. );
  2101. llama.process_system_prompt_data(json::parse(systm_content));
  2102. }
  2103. else if(arg == "--mmproj")
  2104. {
  2105. if (++i >= argc)
  2106. {
  2107. invalid_param = true;
  2108. break;
  2109. }
  2110. params.mmproj = argv[i];
  2111. }
  2112. else if (arg == "--log-disable")
  2113. {
  2114. log_set_target(stdout);
  2115. LOG_INFO("logging to file is disabled.", {});
  2116. }
  2117. else if (arg == "--slots-endpoint-disable")
  2118. {
  2119. sparams.slots_endpoint = false;
  2120. }
  2121. else if (arg == "--chat-template")
  2122. {
  2123. if (++i >= argc)
  2124. {
  2125. invalid_param = true;
  2126. break;
  2127. }
  2128. std::string value(argv[i]);
  2129. if (value != "chatml" && value != "llama2") {
  2130. fprintf(stderr, "error: chat template can be \"llama2\" or \"chatml\", but got: %s\n", value.c_str());
  2131. invalid_param = true;
  2132. break;
  2133. }
  2134. sparams.chat_template = value;
  2135. }
  2136. else if (arg == "--override-kv")
  2137. {
  2138. if (++i >= argc) {
  2139. invalid_param = true;
  2140. break;
  2141. }
  2142. char * sep = strchr(argv[i], '=');
  2143. if (sep == nullptr || sep - argv[i] >= 128) {
  2144. fprintf(stderr, "error: Malformed KV override: %s\n", argv[i]);
  2145. invalid_param = true;
  2146. break;
  2147. }
  2148. struct llama_model_kv_override kvo;
  2149. std::strncpy(kvo.key, argv[i], sep - argv[i]);
  2150. kvo.key[sep - argv[i]] = 0;
  2151. sep++;
  2152. if (strncmp(sep, "int:", 4) == 0) {
  2153. sep += 4;
  2154. kvo.tag = LLAMA_KV_OVERRIDE_INT;
  2155. kvo.int_value = std::atol(sep);
  2156. } else if (strncmp(sep, "float:", 6) == 0) {
  2157. sep += 6;
  2158. kvo.tag = LLAMA_KV_OVERRIDE_FLOAT;
  2159. kvo.float_value = std::atof(sep);
  2160. } else if (strncmp(sep, "bool:", 5) == 0) {
  2161. sep += 5;
  2162. kvo.tag = LLAMA_KV_OVERRIDE_BOOL;
  2163. if (std::strcmp(sep, "true") == 0) {
  2164. kvo.bool_value = true;
  2165. } else if (std::strcmp(sep, "false") == 0) {
  2166. kvo.bool_value = false;
  2167. } else {
  2168. fprintf(stderr, "error: Invalid boolean value for KV override: %s\n", argv[i]);
  2169. invalid_param = true;
  2170. break;
  2171. }
  2172. } else {
  2173. fprintf(stderr, "error: Invalid type for KV override: %s\n", argv[i]);
  2174. invalid_param = true;
  2175. break;
  2176. }
  2177. params.kv_overrides.push_back(kvo);
  2178. }
  2179. else
  2180. {
  2181. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  2182. server_print_usage(argv[0], default_params, default_sparams);
  2183. exit(1);
  2184. }
  2185. }
  2186. if (!params.kv_overrides.empty()) {
  2187. params.kv_overrides.emplace_back();
  2188. params.kv_overrides.back().key[0] = 0;
  2189. }
  2190. if (invalid_param)
  2191. {
  2192. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  2193. server_print_usage(argv[0], default_params, default_sparams);
  2194. exit(1);
  2195. }
  2196. }
  2197. /* llama.cpp completion api semantics */
  2198. static json format_partial_response(
  2199. llama_server_context &llama, llama_client_slot *slot, const std::string &content, const std::vector<completion_token_output> &probs
  2200. ) {
  2201. json res = json
  2202. {
  2203. {"content", content },
  2204. {"stop", false},
  2205. {"slot_id", slot->id },
  2206. {"multimodal", llama.multimodal }
  2207. };
  2208. if (slot->sparams.n_probs > 0)
  2209. {
  2210. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  2211. }
  2212. return res;
  2213. }
  2214. static json format_tokenizer_response(const std::vector<llama_token> &tokens)
  2215. {
  2216. return json{
  2217. {"tokens", tokens}};
  2218. }
  2219. static json format_detokenized_response(std::string content)
  2220. {
  2221. return json{
  2222. {"content", content}};
  2223. }
  2224. static void log_server_request(const httplib::Request &req, const httplib::Response &res)
  2225. {
  2226. LOG_INFO("request", {
  2227. {"remote_addr", req.remote_addr},
  2228. {"remote_port", req.remote_port},
  2229. {"status", res.status},
  2230. {"method", req.method},
  2231. {"path", req.path},
  2232. {"params", req.params},
  2233. });
  2234. LOG_VERBOSE("request", {
  2235. {"request", req.body},
  2236. {"response", res.body},
  2237. });
  2238. }
  2239. struct token_translator
  2240. {
  2241. llama_context * ctx;
  2242. std::string operator()(llama_token tok) const { return llama_token_to_piece(ctx, tok); }
  2243. std::string operator()(const completion_token_output &cto) const { return (*this)(cto.tok); }
  2244. };
  2245. static void append_to_generated_text_from_generated_token_probs(llama_server_context &llama, llama_client_slot *slot)
  2246. {
  2247. auto & gtps = slot->generated_token_probs;
  2248. auto translator = token_translator{llama.ctx};
  2249. auto add_strlen = [=](size_t sum, const completion_token_output & cto) { return sum + translator(cto).size(); };
  2250. const size_t len = std::accumulate(gtps.begin(), gtps.end(), size_t(0), add_strlen);
  2251. if (slot->generated_text.capacity() < slot->generated_text.size() + len)
  2252. {
  2253. slot->generated_text.reserve(slot->generated_text.size() + len);
  2254. }
  2255. for (const completion_token_output & cto : gtps)
  2256. {
  2257. slot->generated_text += translator(cto);
  2258. }
  2259. }
  2260. std::function<void(int)> shutdown_handler;
  2261. inline void signal_handler(int signal) { shutdown_handler(signal); }
  2262. int main(int argc, char **argv)
  2263. {
  2264. #if SERVER_VERBOSE != 1
  2265. log_disable();
  2266. #endif
  2267. // own arguments required by this example
  2268. gpt_params params;
  2269. server_params sparams;
  2270. // struct that contains llama context and inference
  2271. llama_server_context llama;
  2272. server_params_parse(argc, argv, sparams, params, llama);
  2273. if (params.model_alias == "unknown")
  2274. {
  2275. params.model_alias = params.model;
  2276. }
  2277. llama_backend_init();
  2278. llama_numa_init(params.numa);
  2279. LOG_INFO("build info", {{"build", LLAMA_BUILD_NUMBER},
  2280. {"commit", LLAMA_COMMIT}});
  2281. LOG_INFO("system info", {
  2282. {"n_threads", params.n_threads},
  2283. {"n_threads_batch", params.n_threads_batch},
  2284. {"total_threads", std::thread::hardware_concurrency()},
  2285. {"system_info", llama_print_system_info()},
  2286. });
  2287. httplib::Server svr;
  2288. std::atomic<server_state> state{SERVER_STATE_LOADING_MODEL};
  2289. svr.set_default_headers({{"Server", "llama.cpp"}});
  2290. // CORS preflight
  2291. svr.Options(R"(.*)", [](const httplib::Request &req, httplib::Response &res) {
  2292. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2293. res.set_header("Access-Control-Allow-Credentials", "true");
  2294. res.set_header("Access-Control-Allow-Methods", "POST");
  2295. res.set_header("Access-Control-Allow-Headers", "*");
  2296. });
  2297. svr.Get("/health", [&](const httplib::Request&, httplib::Response& res) {
  2298. server_state current_state = state.load();
  2299. switch(current_state) {
  2300. case SERVER_STATE_READY:
  2301. if (llama.all_slots_are_idle) {
  2302. res.set_content(R"({"status": "ok"})", "application/json");
  2303. res.status = 200; // HTTP OK
  2304. } else {
  2305. int available_slots = 0;
  2306. int processing_slots = 0;
  2307. for (llama_client_slot & slot : llama.slots) {
  2308. if (slot.available()) {
  2309. available_slots++;
  2310. } else {
  2311. processing_slots++;
  2312. }
  2313. }
  2314. if (available_slots > 0) {
  2315. json health = {
  2316. {"status", "ok"},
  2317. {"slots_idle", available_slots},
  2318. {"slots_processing", processing_slots}};
  2319. res.set_content(health.dump(), "application/json");
  2320. res.status = 200; // HTTP OK
  2321. } else {
  2322. json health = {
  2323. {"status", "no slot available"},
  2324. {"slots_idle", available_slots},
  2325. {"slots_processing", processing_slots}};
  2326. res.set_content(health.dump(), "application/json");
  2327. res.status = 503; // HTTP Service Unavailable
  2328. }
  2329. }
  2330. break;
  2331. case SERVER_STATE_LOADING_MODEL:
  2332. res.set_content(R"({"status": "loading model"})", "application/json");
  2333. res.status = 503; // HTTP Service Unavailable
  2334. break;
  2335. case SERVER_STATE_ERROR:
  2336. res.set_content(R"({"status": "error", "error": "Model failed to load"})", "application/json");
  2337. res.status = 500; // HTTP Internal Server Error
  2338. break;
  2339. }
  2340. });
  2341. if (sparams.slots_endpoint) {
  2342. svr.Get("/slots", [&](const httplib::Request&, httplib::Response& res) {
  2343. json slots;
  2344. for (llama_client_slot & slot : llama.slots) {
  2345. json slot_data = llama.get_formated_generation(slot);
  2346. slot_data["id"] = slot.id;
  2347. slot_data["task_id"] = slot.task_id;
  2348. slot_data["state"] = slot.state;
  2349. slot_data["prompt"] = slot.prompt;
  2350. slot_data["next_token"] = {
  2351. {"has_next_token", slot.has_next_token},
  2352. {"n_remain", slot.n_remaining},
  2353. {"num_tokens_predicted", slot.n_decoded},
  2354. {"stopped_eos", slot.stopped_eos},
  2355. {"stopped_word", slot.stopped_word},
  2356. {"stopped_limit", slot.stopped_limit},
  2357. {"stopping_word", slot.stopping_word},
  2358. };
  2359. slots.push_back(slot_data);
  2360. }
  2361. res.set_content(slots.dump(), "application/json");
  2362. res.status = 200; // HTTP OK
  2363. });
  2364. }
  2365. svr.set_logger(log_server_request);
  2366. svr.set_exception_handler([](const httplib::Request &, httplib::Response &res, std::exception_ptr ep)
  2367. {
  2368. const char fmt[] = "500 Internal Server Error\n%s";
  2369. char buf[BUFSIZ];
  2370. try
  2371. {
  2372. std::rethrow_exception(std::move(ep));
  2373. }
  2374. catch (std::exception &e)
  2375. {
  2376. snprintf(buf, sizeof(buf), fmt, e.what());
  2377. }
  2378. catch (...)
  2379. {
  2380. snprintf(buf, sizeof(buf), fmt, "Unknown Exception");
  2381. }
  2382. res.set_content(buf, "text/plain; charset=utf-8");
  2383. res.status = 500;
  2384. });
  2385. svr.set_error_handler([](const httplib::Request &, httplib::Response &res)
  2386. {
  2387. if (res.status == 401)
  2388. {
  2389. res.set_content("Unauthorized", "text/plain; charset=utf-8");
  2390. }
  2391. if (res.status == 400)
  2392. {
  2393. res.set_content("Invalid request", "text/plain; charset=utf-8");
  2394. }
  2395. else if (res.status == 404)
  2396. {
  2397. res.set_content("File Not Found", "text/plain; charset=utf-8");
  2398. res.status = 404;
  2399. }
  2400. });
  2401. // set timeouts and change hostname and port
  2402. svr.set_read_timeout (sparams.read_timeout);
  2403. svr.set_write_timeout(sparams.write_timeout);
  2404. if (!svr.bind_to_port(sparams.hostname, sparams.port))
  2405. {
  2406. fprintf(stderr, "\ncouldn't bind to server socket: hostname=%s port=%d\n\n", sparams.hostname.c_str(), sparams.port);
  2407. return 1;
  2408. }
  2409. // Set the base directory for serving static files
  2410. svr.set_base_dir(sparams.public_path);
  2411. // to make it ctrl+clickable:
  2412. LOG_TEE("\nllama server listening at http://%s:%d\n\n", sparams.hostname.c_str(), sparams.port);
  2413. std::unordered_map<std::string, std::string> log_data;
  2414. log_data["hostname"] = sparams.hostname;
  2415. log_data["port"] = std::to_string(sparams.port);
  2416. if (sparams.api_keys.size() == 1) {
  2417. log_data["api_key"] = "api_key: ****" + sparams.api_keys[0].substr(sparams.api_keys[0].length() - 4);
  2418. } else if (sparams.api_keys.size() > 1) {
  2419. log_data["api_key"] = "api_key: " + std::to_string(sparams.api_keys.size()) + " keys loaded";
  2420. }
  2421. LOG_INFO("HTTP server listening", log_data);
  2422. // run the HTTP server in a thread - see comment below
  2423. std::thread t([&]()
  2424. {
  2425. if (!svr.listen_after_bind())
  2426. {
  2427. state.store(SERVER_STATE_ERROR);
  2428. return 1;
  2429. }
  2430. return 0;
  2431. });
  2432. // load the model
  2433. if (!llama.load_model(params))
  2434. {
  2435. state.store(SERVER_STATE_ERROR);
  2436. return 1;
  2437. } else {
  2438. llama.initialize();
  2439. state.store(SERVER_STATE_READY);
  2440. LOG_INFO("model loaded", {});
  2441. }
  2442. // Middleware for API key validation
  2443. auto validate_api_key = [&sparams](const httplib::Request &req, httplib::Response &res) -> bool {
  2444. // If API key is not set, skip validation
  2445. if (sparams.api_keys.empty()) {
  2446. return true;
  2447. }
  2448. // Check for API key in the header
  2449. auto auth_header = req.get_header_value("Authorization");
  2450. std::string prefix = "Bearer ";
  2451. if (auth_header.substr(0, prefix.size()) == prefix) {
  2452. std::string received_api_key = auth_header.substr(prefix.size());
  2453. if (std::find(sparams.api_keys.begin(), sparams.api_keys.end(), received_api_key) != sparams.api_keys.end()) {
  2454. return true; // API key is valid
  2455. }
  2456. }
  2457. // API key is invalid or not provided
  2458. res.set_content("Unauthorized: Invalid API Key", "text/plain; charset=utf-8");
  2459. res.status = 401; // Unauthorized
  2460. LOG_WARNING("Unauthorized: Invalid API Key", {});
  2461. return false;
  2462. };
  2463. // this is only called if no index.html is found in the public --path
  2464. svr.Get("/", [](const httplib::Request &, httplib::Response &res)
  2465. {
  2466. res.set_content(reinterpret_cast<const char*>(&index_html), index_html_len, "text/html; charset=utf-8");
  2467. return false;
  2468. });
  2469. // this is only called if no index.js is found in the public --path
  2470. svr.Get("/index.js", [](const httplib::Request &, httplib::Response &res)
  2471. {
  2472. res.set_content(reinterpret_cast<const char *>(&index_js), index_js_len, "text/javascript; charset=utf-8");
  2473. return false;
  2474. });
  2475. // this is only called if no index.html is found in the public --path
  2476. svr.Get("/completion.js", [](const httplib::Request &, httplib::Response &res)
  2477. {
  2478. res.set_content(reinterpret_cast<const char*>(&completion_js), completion_js_len, "application/javascript; charset=utf-8");
  2479. return false;
  2480. });
  2481. // this is only called if no index.html is found in the public --path
  2482. svr.Get("/json-schema-to-grammar.mjs", [](const httplib::Request &, httplib::Response &res)
  2483. {
  2484. res.set_content(reinterpret_cast<const char*>(&json_schema_to_grammar_mjs), json_schema_to_grammar_mjs_len, "application/javascript; charset=utf-8");
  2485. return false;
  2486. });
  2487. svr.Get("/props", [&llama](const httplib::Request & req, httplib::Response &res)
  2488. {
  2489. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2490. json data = {
  2491. { "user_name", llama.name_user.c_str() },
  2492. { "assistant_name", llama.name_assistant.c_str() },
  2493. { "default_generation_settings", llama.default_generation_settings_for_props },
  2494. { "total_slots", llama.params.n_parallel }
  2495. };
  2496. res.set_content(data.dump(), "application/json; charset=utf-8");
  2497. });
  2498. svr.Post("/completion", [&llama, &validate_api_key](const httplib::Request &req, httplib::Response &res)
  2499. {
  2500. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2501. if (!validate_api_key(req, res)) {
  2502. return;
  2503. }
  2504. json data = json::parse(req.body);
  2505. const int task_id = llama.queue_tasks.get_new_id();
  2506. llama.queue_results.add_waiting_task_id(task_id);
  2507. llama.request_completion(task_id, data, false, false, -1);
  2508. if (!json_value(data, "stream", false)) {
  2509. std::string completion_text;
  2510. task_result result = llama.queue_results.recv(task_id);
  2511. if (!result.error && result.stop) {
  2512. res.set_content(result.result_json.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  2513. }
  2514. else
  2515. {
  2516. res.status = 404;
  2517. res.set_content(result.result_json["content"], "text/plain; charset=utf-8");
  2518. }
  2519. llama.queue_results.remove_waiting_task_id(task_id);
  2520. } else {
  2521. const auto chunked_content_provider = [task_id, &llama](size_t, httplib::DataSink & sink)
  2522. {
  2523. while (true)
  2524. {
  2525. task_result result = llama.queue_results.recv(task_id);
  2526. if (!result.error) {
  2527. const std::string str =
  2528. "data: " +
  2529. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace) +
  2530. "\n\n";
  2531. LOG_VERBOSE("data stream", {
  2532. { "to_send", str }
  2533. });
  2534. if (!sink.write(str.c_str(), str.size()))
  2535. {
  2536. llama.queue_results.remove_waiting_task_id(task_id);
  2537. return false;
  2538. }
  2539. if (result.stop) {
  2540. break;
  2541. }
  2542. } else {
  2543. const std::string str =
  2544. "error: " +
  2545. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace) +
  2546. "\n\n";
  2547. LOG_VERBOSE("data stream", {
  2548. { "to_send", str }
  2549. });
  2550. if (!sink.write(str.c_str(), str.size()))
  2551. {
  2552. llama.queue_results.remove_waiting_task_id(task_id);
  2553. return false;
  2554. }
  2555. break;
  2556. }
  2557. }
  2558. llama.queue_results.remove_waiting_task_id(task_id);
  2559. sink.done();
  2560. return true;
  2561. };
  2562. auto on_complete = [task_id, &llama] (bool)
  2563. {
  2564. // cancel
  2565. llama.request_cancel(task_id);
  2566. llama.queue_results.remove_waiting_task_id(task_id);
  2567. };
  2568. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2569. }
  2570. });
  2571. svr.Get("/v1/models", [&params](const httplib::Request& req, httplib::Response& res)
  2572. {
  2573. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2574. std::time_t t = std::time(0);
  2575. json models = {
  2576. {"object", "list"},
  2577. {"data", {
  2578. {
  2579. {"id", params.model_alias},
  2580. {"object", "model"},
  2581. {"created", t},
  2582. {"owned_by", "llamacpp"}
  2583. },
  2584. }}
  2585. };
  2586. res.set_content(models.dump(), "application/json; charset=utf-8");
  2587. });
  2588. // TODO: add mount point without "/v1" prefix -- how?
  2589. svr.Post("/v1/chat/completions", [&llama, &validate_api_key, &sparams](const httplib::Request &req, httplib::Response &res)
  2590. {
  2591. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2592. if (!validate_api_key(req, res)) {
  2593. return;
  2594. }
  2595. json data = oaicompat_completion_params_parse(json::parse(req.body), sparams.chat_template);
  2596. const int task_id = llama.queue_tasks.get_new_id();
  2597. llama.queue_results.add_waiting_task_id(task_id);
  2598. llama.request_completion(task_id, data, false, false, -1);
  2599. if (!json_value(data, "stream", false)) {
  2600. std::string completion_text;
  2601. task_result result = llama.queue_results.recv(task_id);
  2602. if (!result.error && result.stop) {
  2603. json oaicompat_result = format_final_response_oaicompat(data, result);
  2604. res.set_content(oaicompat_result.dump(-1, ' ', false,
  2605. json::error_handler_t::replace),
  2606. "application/json; charset=utf-8");
  2607. } else {
  2608. res.status = 500;
  2609. res.set_content(result.result_json["content"], "text/plain; charset=utf-8");
  2610. }
  2611. llama.queue_results.remove_waiting_task_id(task_id);
  2612. } else {
  2613. const auto chunked_content_provider = [task_id, &llama](size_t, httplib::DataSink &sink) {
  2614. while (true) {
  2615. task_result llama_result = llama.queue_results.recv(task_id);
  2616. if (!llama_result.error) {
  2617. std::vector<json> result_array = format_partial_response_oaicompat( llama_result);
  2618. for (auto it = result_array.begin(); it != result_array.end(); ++it)
  2619. {
  2620. if (!it->empty()) {
  2621. const std::string str =
  2622. "data: " +
  2623. it->dump(-1, ' ', false, json::error_handler_t::replace) +
  2624. "\n\n";
  2625. LOG_VERBOSE("data stream", {{"to_send", str}});
  2626. if (!sink.write(str.c_str(), str.size())) {
  2627. llama.queue_results.remove_waiting_task_id(task_id);
  2628. return false;
  2629. }
  2630. }
  2631. }
  2632. if (llama_result.stop) {
  2633. break;
  2634. }
  2635. } else {
  2636. const std::string str =
  2637. "error: " +
  2638. llama_result.result_json.dump(-1, ' ', false,
  2639. json::error_handler_t::replace) +
  2640. "\n\n";
  2641. LOG_VERBOSE("data stream", {{"to_send", str}});
  2642. if (!sink.write(str.c_str(), str.size())) {
  2643. llama.queue_results.remove_waiting_task_id(task_id);
  2644. return false;
  2645. }
  2646. break;
  2647. }
  2648. }
  2649. sink.done();
  2650. llama.queue_results.remove_waiting_task_id(task_id);
  2651. return true;
  2652. };
  2653. auto on_complete = [task_id, &llama](bool) {
  2654. // cancel request
  2655. llama.request_cancel(task_id);
  2656. llama.queue_results.remove_waiting_task_id(task_id);
  2657. };
  2658. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2659. }
  2660. });
  2661. svr.Post("/infill", [&llama, &validate_api_key](const httplib::Request &req, httplib::Response &res)
  2662. {
  2663. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2664. if (!validate_api_key(req, res)) {
  2665. return;
  2666. }
  2667. json data = json::parse(req.body);
  2668. const int task_id = llama.queue_tasks.get_new_id();
  2669. llama.queue_results.add_waiting_task_id(task_id);
  2670. llama.request_completion(task_id, data, true, false, -1);
  2671. if (!json_value(data, "stream", false)) {
  2672. std::string completion_text;
  2673. task_result result = llama.queue_results.recv(task_id);
  2674. if (!result.error && result.stop)
  2675. {
  2676. res.set_content(result.result_json.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  2677. }
  2678. else
  2679. {
  2680. res.status = 404;
  2681. res.set_content(result.result_json["content"], "text/plain; charset=utf-8");
  2682. }
  2683. llama.queue_results.remove_waiting_task_id(task_id);
  2684. } else {
  2685. const auto chunked_content_provider = [task_id, &llama](size_t, httplib::DataSink & sink) {
  2686. while (true)
  2687. {
  2688. task_result result = llama.queue_results.recv(task_id);
  2689. if (!result.error) {
  2690. const std::string str =
  2691. "data: " +
  2692. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace) +
  2693. "\n\n";
  2694. LOG_VERBOSE("data stream", {
  2695. { "to_send", str }
  2696. });
  2697. if (!sink.write(str.c_str(), str.size()))
  2698. {
  2699. llama.queue_results.remove_waiting_task_id(task_id);
  2700. return false;
  2701. }
  2702. if (result.stop)
  2703. {
  2704. break;
  2705. }
  2706. }
  2707. else
  2708. {
  2709. break;
  2710. }
  2711. }
  2712. llama.queue_results.remove_waiting_task_id(task_id);
  2713. sink.done();
  2714. return true;
  2715. };
  2716. auto on_complete = [task_id, &llama] (bool)
  2717. {
  2718. // cancel
  2719. llama.request_cancel(task_id);
  2720. };
  2721. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2722. }
  2723. });
  2724. svr.Options(R"(/.*)", [](const httplib::Request &, httplib::Response &res)
  2725. { return res.set_content("", "application/json; charset=utf-8"); });
  2726. svr.Post("/tokenize", [&llama](const httplib::Request &req, httplib::Response &res)
  2727. {
  2728. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2729. const json body = json::parse(req.body);
  2730. std::vector<llama_token> tokens;
  2731. if (body.count("content") != 0)
  2732. {
  2733. tokens = llama.tokenize(body["content"], false);
  2734. }
  2735. const json data = format_tokenizer_response(tokens);
  2736. return res.set_content(data.dump(), "application/json; charset=utf-8");
  2737. });
  2738. svr.Post("/detokenize", [&llama](const httplib::Request &req, httplib::Response &res)
  2739. {
  2740. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2741. const json body = json::parse(req.body);
  2742. std::string content;
  2743. if (body.count("tokens") != 0)
  2744. {
  2745. const std::vector<llama_token> tokens = body["tokens"];
  2746. content = tokens_to_str(llama.ctx, tokens.cbegin(), tokens.cend());
  2747. }
  2748. const json data = format_detokenized_response(content);
  2749. return res.set_content(data.dump(), "application/json; charset=utf-8");
  2750. });
  2751. svr.Post("/embedding", [&llama](const httplib::Request &req, httplib::Response &res)
  2752. {
  2753. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2754. const json body = json::parse(req.body);
  2755. json prompt;
  2756. if (body.count("content") != 0)
  2757. {
  2758. prompt = body["content"];
  2759. }
  2760. else
  2761. {
  2762. prompt = "";
  2763. }
  2764. json image_data;
  2765. if (body.count("image_data") != 0) {
  2766. image_data = body["image_data"];
  2767. }
  2768. else
  2769. {
  2770. image_data = "";
  2771. }
  2772. // create and queue the task
  2773. const int task_id = llama.queue_tasks.get_new_id();
  2774. llama.queue_results.add_waiting_task_id(task_id);
  2775. llama.request_completion(task_id, { {"prompt", prompt}, { "n_predict", 0}, {"image_data", image_data} }, false, true, -1);
  2776. // get the result
  2777. task_result result = llama.queue_results.recv(task_id);
  2778. llama.queue_results.remove_waiting_task_id(task_id);
  2779. // send the result
  2780. return res.set_content(result.result_json.dump(), "application/json; charset=utf-8");
  2781. });
  2782. svr.Post("/v1/embeddings", [&llama](const httplib::Request &req, httplib::Response &res)
  2783. {
  2784. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2785. const json body = json::parse(req.body);
  2786. json prompt;
  2787. if (body.count("input") != 0)
  2788. {
  2789. prompt = body["input"];
  2790. // batch
  2791. if(prompt.is_array()) {
  2792. json data = json::array();
  2793. int i = 0;
  2794. for (const json &elem : prompt) {
  2795. const int task_id = llama.queue_tasks.get_new_id();
  2796. llama.queue_results.add_waiting_task_id(task_id);
  2797. llama.request_completion(task_id, { {"prompt", elem}, { "n_predict", 0} }, false, true, -1);
  2798. // get the result
  2799. task_result result = llama.queue_results.recv(task_id);
  2800. llama.queue_results.remove_waiting_task_id(task_id);
  2801. json embedding = json{
  2802. {"embedding", json_value(result.result_json, "embedding", json::array())},
  2803. {"index", i++},
  2804. {"object", "embedding"}
  2805. };
  2806. data.push_back(embedding);
  2807. }
  2808. json result = format_embeddings_response_oaicompat(body, data);
  2809. return res.set_content(result.dump(), "application/json; charset=utf-8");
  2810. }
  2811. }
  2812. else
  2813. {
  2814. prompt = "";
  2815. }
  2816. // create and queue the task
  2817. const int task_id = llama.queue_tasks.get_new_id();
  2818. llama.queue_results.add_waiting_task_id(task_id);
  2819. llama.request_completion(task_id, { {"prompt", prompt}, { "n_predict", 0}}, false, true, -1);
  2820. // get the result
  2821. task_result result = llama.queue_results.recv(task_id);
  2822. llama.queue_results.remove_waiting_task_id(task_id);
  2823. json data = json::array({json{
  2824. {"embedding", json_value(result.result_json, "embedding", json::array())},
  2825. {"index", 0},
  2826. {"object", "embedding"}
  2827. }}
  2828. );
  2829. json root = format_embeddings_response_oaicompat(body, data);
  2830. // send the result
  2831. return res.set_content(root.dump(), "application/json; charset=utf-8");
  2832. });
  2833. // GG: if I put the main loop inside a thread, it crashes on the first request when build in Debug!?
  2834. // "Bus error: 10" - this is on macOS, it does not crash on Linux
  2835. //std::thread t2([&]()
  2836. /*{
  2837. bool running = true;
  2838. while (running)
  2839. {
  2840. running = llama.update_slots();
  2841. }
  2842. }*/
  2843. //);
  2844. llama.queue_tasks.on_new_task(std::bind(
  2845. &llama_server_context::process_single_task, &llama, std::placeholders::_1));
  2846. llama.queue_tasks.on_finish_multitask(std::bind(
  2847. &llama_server_context::on_finish_multitask, &llama, std::placeholders::_1));
  2848. llama.queue_tasks.on_all_tasks_finished(std::bind(
  2849. &llama_server_context::run_on_all_tasks_finished, &llama));
  2850. llama.queue_results.on_multitask_update(std::bind(
  2851. &llama_server_queue::update_multitask,
  2852. &llama.queue_tasks,
  2853. std::placeholders::_1,
  2854. std::placeholders::_2,
  2855. std::placeholders::_3
  2856. ));
  2857. shutdown_handler = [&](int) {
  2858. llama.queue_tasks.terminate();
  2859. };
  2860. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  2861. struct sigaction sigint_action;
  2862. sigint_action.sa_handler = signal_handler;
  2863. sigemptyset (&sigint_action.sa_mask);
  2864. sigint_action.sa_flags = 0;
  2865. sigaction(SIGINT, &sigint_action, NULL);
  2866. #elif defined (_WIN32)
  2867. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  2868. return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
  2869. };
  2870. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  2871. #endif
  2872. llama.queue_tasks.start_loop();
  2873. svr.stop();
  2874. t.join();
  2875. llama_backend_free();
  2876. return 0;
  2877. }