1
0

server.cpp 115 KB

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