server.cpp 120 KB

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