server.cpp 120 KB

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