1
0

server.cpp 119 KB

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