1
0

server.cpp 117 KB

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