server.cpp 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #include "grammar-parser.h"
  5. #include "../llava/clip.h"
  6. #include "stb_image.h"
  7. #ifndef NDEBUG
  8. // crash the server in debug mode, otherwise send an http 500 error
  9. #define CPPHTTPLIB_NO_EXCEPTIONS 1
  10. #endif
  11. #include "httplib.h"
  12. #include "json.hpp"
  13. // auto generated files (update with ./deps.sh)
  14. #include "index.html.hpp"
  15. #include "index.js.hpp"
  16. #include "completion.js.hpp"
  17. #include "json-schema-to-grammar.mjs.hpp"
  18. #include <cstddef>
  19. #include <thread>
  20. #include <mutex>
  21. #include <chrono>
  22. #ifndef SERVER_VERBOSE
  23. #define SERVER_VERBOSE 1
  24. #endif
  25. using json = nlohmann::json;
  26. struct server_params
  27. {
  28. std::string hostname = "127.0.0.1";
  29. std::string public_path = "examples/server/public";
  30. int32_t port = 8080;
  31. int32_t read_timeout = 600;
  32. int32_t write_timeout = 600;
  33. };
  34. static bool server_verbose = false;
  35. #if SERVER_VERBOSE != 1
  36. #define LOG_VERBOSE(MSG, ...)
  37. #else
  38. #define LOG_VERBOSE(MSG, ...) \
  39. do \
  40. { \
  41. if (server_verbose) \
  42. { \
  43. server_log("VERBOSE", __func__, __LINE__, MSG, __VA_ARGS__); \
  44. } \
  45. } while (0)
  46. #endif
  47. #define LOG_ERROR( MSG, ...) server_log("ERROR", __func__, __LINE__, MSG, __VA_ARGS__)
  48. #define LOG_WARNING(MSG, ...) server_log("WARNING", __func__, __LINE__, MSG, __VA_ARGS__)
  49. #define LOG_INFO( MSG, ...) server_log("INFO", __func__, __LINE__, MSG, __VA_ARGS__)
  50. //
  51. // base64 utils (TODO: move to common in the future)
  52. //
  53. static const std::string base64_chars =
  54. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  55. "abcdefghijklmnopqrstuvwxyz"
  56. "0123456789+/";
  57. static inline bool is_base64(uint8_t c)
  58. {
  59. return (isalnum(c) || (c == '+') || (c == '/'));
  60. }
  61. static std::vector<uint8_t> base64_decode(std::string const &encoded_string)
  62. {
  63. int i = 0;
  64. int j = 0;
  65. int in_ = 0;
  66. int in_len = encoded_string.size();
  67. uint8_t char_array_4[4];
  68. uint8_t char_array_3[3];
  69. std::vector<uint8_t> ret;
  70. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_]))
  71. {
  72. char_array_4[i++] = encoded_string[in_]; in_++;
  73. if (i == 4)
  74. {
  75. for (i = 0; i <4; i++)
  76. {
  77. char_array_4[i] = base64_chars.find(char_array_4[i]);
  78. }
  79. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  80. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  81. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  82. for (i = 0; (i < 3); i++)
  83. {
  84. ret.push_back(char_array_3[i]);
  85. }
  86. i = 0;
  87. }
  88. }
  89. if (i)
  90. {
  91. for (j = i; j <4; j++)
  92. {
  93. char_array_4[j] = 0;
  94. }
  95. for (j = 0; j <4; j++)
  96. {
  97. char_array_4[j] = base64_chars.find(char_array_4[j]);
  98. }
  99. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  100. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  101. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  102. for (j = 0; (j < i - 1); j++)
  103. {
  104. ret.push_back(char_array_3[j]);
  105. }
  106. }
  107. return ret;
  108. }
  109. //
  110. // parallel
  111. //
  112. enum task_type {
  113. COMPLETION_TASK,
  114. CANCEL_TASK
  115. };
  116. struct task_server {
  117. int id;
  118. int target_id;
  119. task_type type;
  120. json data;
  121. bool infill_mode = false;
  122. };
  123. struct task_result {
  124. int id;
  125. bool stop;
  126. bool error;
  127. json result_json;
  128. };
  129. // TODO: can become bool if we can't find use of more states
  130. enum slot_state
  131. {
  132. IDLE,
  133. PROCESSING,
  134. };
  135. enum slot_command
  136. {
  137. NONE,
  138. LOAD_PROMPT,
  139. RELEASE,
  140. };
  141. struct slot_params
  142. {
  143. bool stream = true;
  144. bool cache_prompt = false; // remember the prompt to avoid reprocessing all prompt
  145. uint32_t seed = -1; // RNG seed
  146. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  147. int32_t n_predict = -1; // new tokens to predict
  148. std::vector<std::string> antiprompt;
  149. json input_prefix;
  150. json input_suffix;
  151. };
  152. struct slot_image
  153. {
  154. int32_t id;
  155. bool request_encode_image = false;
  156. float* image_embedding = nullptr;
  157. int32_t image_tokens = 0;
  158. clip_image_u8 img_data;
  159. std::string prefix_prompt; // before of this image
  160. };
  161. // completion token output with probabilities
  162. struct completion_token_output
  163. {
  164. struct token_prob
  165. {
  166. llama_token tok;
  167. float prob;
  168. };
  169. std::vector<token_prob> probs;
  170. llama_token tok;
  171. std::string text_to_send;
  172. };
  173. static size_t common_part(const std::vector<llama_token> &a, const std::vector<llama_token> &b)
  174. {
  175. size_t i;
  176. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++)
  177. {
  178. }
  179. return i;
  180. }
  181. enum stop_type
  182. {
  183. STOP_FULL,
  184. STOP_PARTIAL,
  185. };
  186. static bool ends_with(const std::string &str, const std::string &suffix)
  187. {
  188. return str.size() >= suffix.size() &&
  189. 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  190. }
  191. static size_t find_partial_stop_string(const std::string &stop,
  192. const std::string &text)
  193. {
  194. if (!text.empty() && !stop.empty())
  195. {
  196. const char text_last_char = text.back();
  197. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--)
  198. {
  199. if (stop[char_index] == text_last_char)
  200. {
  201. const std::string current_partial = stop.substr(0, char_index + 1);
  202. if (ends_with(text, current_partial))
  203. {
  204. return text.size() - char_index - 1;
  205. }
  206. }
  207. }
  208. }
  209. return std::string::npos;
  210. }
  211. // TODO: reuse llama_detokenize
  212. template <class Iter>
  213. static std::string tokens_to_str(llama_context *ctx, Iter begin, Iter end)
  214. {
  215. std::string ret;
  216. for (; begin != end; ++begin)
  217. {
  218. ret += llama_token_to_piece(ctx, *begin);
  219. }
  220. return ret;
  221. }
  222. static void server_log(const char *level, const char *function, int line,
  223. const char *message, const nlohmann::ordered_json &extra)
  224. {
  225. nlohmann::ordered_json log
  226. {
  227. {"timestamp", time(nullptr)},
  228. {"level", level},
  229. {"function", function},
  230. {"line", line},
  231. {"message", message},
  232. };
  233. if (!extra.empty())
  234. {
  235. log.merge_patch(extra);
  236. }
  237. const std::string str = log.dump(-1, ' ', false, json::error_handler_t::replace);
  238. printf("%.*s\n", (int)str.size(), str.data());
  239. fflush(stdout);
  240. }
  241. // format incomplete utf-8 multibyte character for output
  242. static std::string tokens_to_output_formatted_string(const llama_context *ctx, const llama_token token)
  243. {
  244. std::string out = token == -1 ? "" : llama_token_to_piece(ctx, token);
  245. // if the size is 1 and first bit is 1, meaning it's a partial character
  246. // (size > 1 meaning it's already a known token)
  247. if (out.size() == 1 && (out[0] & 0x80) == 0x80)
  248. {
  249. std::stringstream ss;
  250. ss << std::hex << (out[0] & 0xff);
  251. std::string res(ss.str());
  252. out = "byte: \\x" + res;
  253. }
  254. return out;
  255. }
  256. // convert a vector of completion_token_output to json
  257. static json probs_vector_to_json(const llama_context *ctx, const std::vector<completion_token_output> &probs)
  258. {
  259. json out = json::array();
  260. for (const auto &prob : probs)
  261. {
  262. json probs_for_token = json::array();
  263. for (const auto &p : prob.probs)
  264. {
  265. std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
  266. probs_for_token.push_back(json
  267. {
  268. {"tok_str", tok_str},
  269. {"prob", p.prob},
  270. });
  271. }
  272. std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
  273. out.push_back(json{
  274. {"content", tok_str},
  275. {"probs", probs_for_token},
  276. });
  277. }
  278. return out;
  279. }
  280. template <typename T>
  281. static T json_value(const json &body, const std::string &key, const T &default_value)
  282. {
  283. // Fallback null to default value
  284. return body.contains(key) && !body.at(key).is_null()
  285. ? body.value(key, default_value)
  286. : default_value;
  287. }
  288. struct llama_client_slot
  289. {
  290. int id;
  291. int task_id = -1;
  292. struct slot_params params;
  293. slot_state state = IDLE;
  294. slot_command command = NONE;
  295. // used to determine the slot that has been used the longest
  296. int64_t t_last_used = -1;
  297. // generation props
  298. int32_t n_ctx = 0; // context size per slot
  299. int32_t n_past = 0;
  300. int32_t n_decoded = 0;
  301. int32_t n_remaining = -1;
  302. int32_t i_batch = -1;
  303. int32_t num_prompt_tokens = 0;
  304. int32_t num_prompt_tokens_processed = 0;
  305. int32_t multibyte_pending = 0;
  306. json prompt;
  307. std::string generated_text;
  308. llama_token sampled;
  309. std::vector<llama_token> cache_tokens;
  310. std::vector<completion_token_output> generated_token_probs;
  311. bool infill = false;
  312. bool has_next_token = true;
  313. bool truncated = false;
  314. bool stopped_eos = false;
  315. bool stopped_word = false;
  316. bool stopped_limit = false;
  317. std::string stopping_word;
  318. // sampling
  319. struct llama_sampling_params sparams;
  320. llama_sampling_context *ctx_sampling = nullptr;
  321. // multimodal
  322. std::vector<slot_image> images;
  323. // stats
  324. size_t sent_count = 0;
  325. size_t sent_token_probs_index = 0;
  326. int64_t t_start_process_prompt;
  327. int64_t t_start_genereration;
  328. double t_prompt_processing; // ms
  329. double t_token_generation; // ms
  330. void reset() {
  331. num_prompt_tokens = 0;
  332. generated_text = "";
  333. truncated = false;
  334. stopped_eos = false;
  335. stopped_word = false;
  336. stopped_limit = false;
  337. stopping_word = "";
  338. multibyte_pending = 0;
  339. n_past = 0;
  340. sent_count = 0;
  341. sent_token_probs_index = 0;
  342. infill = false;
  343. generated_token_probs.clear();
  344. for (slot_image &img : images)
  345. {
  346. free(img.image_embedding);
  347. delete[] img.img_data.data;
  348. img.prefix_prompt = "";
  349. }
  350. images.clear();
  351. // llama_set_rng_seed(ctx, params.seed); in batched the seed matter???????
  352. }
  353. bool has_budget(gpt_params &global_params) {
  354. n_remaining = -1;
  355. if(params.n_predict != -1)
  356. {
  357. n_remaining = params.n_predict - n_decoded;
  358. }
  359. else if (global_params.n_predict != -1)
  360. {
  361. n_remaining = global_params.n_predict - n_decoded;
  362. }
  363. return n_remaining > 0 || n_remaining == -1; // no budget || limitless
  364. }
  365. bool available() const {
  366. return state == IDLE && command == NONE;
  367. }
  368. bool is_processing() const {
  369. return (state == IDLE && command == LOAD_PROMPT) || state == PROCESSING;
  370. }
  371. void add_token_string(const completion_token_output &token) {
  372. if (command == RELEASE)
  373. {
  374. return;
  375. }
  376. cache_tokens.push_back(token.tok);
  377. generated_token_probs.push_back(token);
  378. }
  379. void release() {
  380. if (state == IDLE || state == PROCESSING)
  381. {
  382. t_token_generation = (ggml_time_us() - t_start_genereration) / 1e3;
  383. command = RELEASE;
  384. }
  385. }
  386. json get_formated_timings() {
  387. return json
  388. {
  389. {"prompt_n", num_prompt_tokens_processed},
  390. {"prompt_ms", t_prompt_processing},
  391. {"prompt_per_token_ms", t_prompt_processing / num_prompt_tokens_processed},
  392. {"prompt_per_second", 1e3 / t_prompt_processing * num_prompt_tokens_processed},
  393. {"predicted_n", n_decoded},
  394. {"predicted_ms", t_token_generation},
  395. {"predicted_per_token_ms", t_token_generation / n_decoded},
  396. {"predicted_per_second", 1e3 / t_token_generation * n_decoded},
  397. };
  398. }
  399. void print_timings() {
  400. LOG_TEE("\n");
  401. LOG_TEE("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  402. __func__, t_prompt_processing, num_prompt_tokens_processed, t_prompt_processing / num_prompt_tokens_processed, 1e3 / t_prompt_processing * num_prompt_tokens_processed);
  403. LOG_TEE("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  404. __func__, t_token_generation, n_decoded,t_token_generation / n_decoded, 1e3 / t_token_generation * n_decoded);
  405. LOG_TEE("%s: total time = %10.2f ms\n", __func__, t_prompt_processing + t_token_generation);
  406. }
  407. };
  408. struct llama_server_context
  409. {
  410. llama_model *model = nullptr;
  411. llama_context *ctx = nullptr;
  412. clip_ctx *clp_ctx = nullptr;
  413. gpt_params params;
  414. llama_batch batch;
  415. bool multimodal = false;
  416. bool clean_kv_cache = true;
  417. bool all_slots_are_idle = false;
  418. int32_t id_gen;
  419. int32_t n_ctx; // total context for all clients / slots
  420. // system prompt
  421. bool system_need_update = false;
  422. std::string system_prompt;
  423. std::vector<llama_token> system_tokens;
  424. std::string name_user; // this should be the antiprompt
  425. std::string name_assistant;
  426. // slots / clients
  427. std::vector<llama_client_slot> slots;
  428. std::vector<task_server> queue_tasks;
  429. std::vector<task_result> queue_results;
  430. std::mutex mutex_tasks;
  431. std::mutex mutex_results;
  432. ~llama_server_context()
  433. {
  434. if (ctx)
  435. {
  436. llama_free(ctx);
  437. ctx = nullptr;
  438. }
  439. if (model)
  440. {
  441. llama_free_model(model);
  442. model = nullptr;
  443. }
  444. }
  445. bool load_model(const gpt_params &params_)
  446. {
  447. params = params_;
  448. if (!params.mmproj.empty()) {
  449. multimodal = true;
  450. LOG_TEE("Multi Modal Mode Enabled");
  451. clp_ctx = clip_model_load(params.mmproj.c_str(), /*verbosity=*/ 1);
  452. if(clp_ctx == nullptr) {
  453. LOG_ERROR("unable to load clip model", {{"model", params.mmproj}});
  454. return false;
  455. }
  456. if (params.n_ctx < 2048) { // request larger context for the image embedding
  457. params.n_ctx = 2048;
  458. }
  459. }
  460. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  461. if (model == nullptr)
  462. {
  463. LOG_ERROR("unable to load model", {{"model", params.model}});
  464. return false;
  465. }
  466. if (multimodal) {
  467. const int n_embd_clip = clip_n_mmproj_embd(clp_ctx);
  468. const int n_embd_llm = llama_n_embd(model);
  469. if (n_embd_clip != n_embd_llm) {
  470. 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);
  471. llama_free(ctx);
  472. llama_free_model(model);
  473. return false;
  474. }
  475. }
  476. n_ctx = llama_n_ctx(ctx);
  477. return true;
  478. }
  479. void initialize() {
  480. id_gen = 0;
  481. // create slots
  482. all_slots_are_idle = true;
  483. const int32_t n_ctx_slot = n_ctx / params.n_parallel;
  484. LOG_TEE("Available slots:\n");
  485. for (int i = 0; i < params.n_parallel; i++)
  486. {
  487. llama_client_slot slot;
  488. slot.id = i;
  489. slot.n_ctx = n_ctx_slot;
  490. slot.reset();
  491. LOG_TEE(" -> Slot %i - max context: %i\n", slot.id, n_ctx_slot);
  492. slots.push_back(slot);
  493. }
  494. batch = llama_batch_init(n_ctx, 0, params.n_parallel);
  495. // empty system prompt
  496. system_prompt = "";
  497. system_tokens.clear();
  498. }
  499. std::vector<llama_token> tokenize(const json & json_prompt, bool add_bos) const
  500. {
  501. // If `add_bos` is true, we only add BOS, when json_prompt is a string,
  502. // or the first element of the json_prompt array is a string.
  503. std::vector<llama_token> prompt_tokens;
  504. if (json_prompt.is_array())
  505. {
  506. bool first = true;
  507. for (const auto& p : json_prompt)
  508. {
  509. if (p.is_string())
  510. {
  511. auto s = p.template get<std::string>();
  512. std::vector<llama_token> p;
  513. if (first)
  514. {
  515. p = ::llama_tokenize(ctx, s, add_bos);
  516. first = false;
  517. }
  518. else
  519. {
  520. p = ::llama_tokenize(ctx, s, false);
  521. }
  522. prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
  523. }
  524. else
  525. {
  526. if (first)
  527. {
  528. first = false;
  529. }
  530. prompt_tokens.push_back(p.template get<llama_token>());
  531. }
  532. }
  533. }
  534. else
  535. {
  536. auto s = json_prompt.template get<std::string>();
  537. prompt_tokens = ::llama_tokenize(ctx, s, add_bos);
  538. }
  539. return prompt_tokens;
  540. }
  541. llama_client_slot* get_slot(int id) {
  542. int64_t t_last = ggml_time_us();
  543. llama_client_slot *last_used = nullptr;
  544. for (llama_client_slot & slot : slots)
  545. {
  546. if (slot.id == id && slot.available())
  547. {
  548. return &slot;
  549. }
  550. if (slot.available() && slot.t_last_used < t_last)
  551. {
  552. last_used = &slot;
  553. t_last = slot.t_last_used;
  554. }
  555. }
  556. return last_used;
  557. }
  558. bool launch_slot_with_data(llama_client_slot* &slot, json data) {
  559. slot_params default_params;
  560. llama_sampling_params default_sparams;
  561. slot->params.stream = json_value(data, "stream", false);
  562. slot->params.cache_prompt = json_value(data, "cache_prompt", false);
  563. slot->params.n_predict = json_value(data, "n_predict", default_params.n_predict);
  564. slot->sparams.top_k = json_value(data, "top_k", default_sparams.top_k);
  565. slot->sparams.top_p = json_value(data, "top_p", default_sparams.top_p);
  566. slot->sparams.tfs_z = json_value(data, "tfs_z", default_sparams.tfs_z);
  567. slot->sparams.typical_p = json_value(data, "typical_p", default_sparams.typical_p);
  568. slot->sparams.temp = json_value(data, "temperature", default_sparams.temp);
  569. slot->sparams.penalty_last_n = json_value(data, "repeat_last_n", default_sparams.penalty_last_n);
  570. slot->sparams.penalty_repeat = json_value(data, "repeat_penalty", default_sparams.penalty_repeat);
  571. slot->sparams.penalty_freq = json_value(data, "frequency_penalty", default_sparams.penalty_freq);
  572. slot->sparams.penalty_present = json_value(data, "presence_penalty", default_sparams.penalty_present);
  573. slot->sparams.mirostat = json_value(data, "mirostat", default_sparams.mirostat);
  574. slot->sparams.mirostat_tau = json_value(data, "mirostat_tau", default_sparams.mirostat_tau);
  575. slot->sparams.mirostat_eta = json_value(data, "mirostat_eta", default_sparams.mirostat_eta);
  576. slot->sparams.penalize_nl = json_value(data, "penalize_nl", default_sparams.penalize_nl);
  577. slot->params.n_keep = json_value(data, "n_keep", slot->params.n_keep);
  578. slot->params.seed = json_value(data, "seed", default_params.seed);
  579. slot->sparams.grammar = json_value(data, "grammar", default_sparams.grammar);
  580. slot->sparams.n_probs = json_value(data, "n_probs", default_sparams.n_probs);
  581. // infill
  582. if (data.count("input_prefix") != 0)
  583. {
  584. slot->params.input_prefix = data["input_prefix"];
  585. }
  586. else
  587. {
  588. slot->params.input_prefix = "";
  589. }
  590. if (data.count("input_suffix") != 0)
  591. {
  592. slot->params.input_suffix = data["input_suffix"];
  593. }
  594. else
  595. {
  596. slot->params.input_suffix = "";
  597. }
  598. if (data.count("prompt") != 0)
  599. {
  600. slot->prompt = data["prompt"];
  601. }
  602. else
  603. {
  604. slot->prompt = "";
  605. }
  606. slot->sparams.logit_bias.clear();
  607. if (json_value(data, "ignore_eos", false))
  608. {
  609. slot->sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  610. }
  611. const auto &logit_bias = data.find("logit_bias");
  612. if (logit_bias != data.end() && logit_bias->is_array())
  613. {
  614. const int n_vocab = llama_n_vocab(model);
  615. for (const auto &el : *logit_bias)
  616. {
  617. if (el.is_array() && el.size() == 2 && el[0].is_number_integer())
  618. {
  619. llama_token tok = el[0].get<llama_token>();
  620. if (tok >= 0 && tok < n_vocab)
  621. {
  622. if (el[1].is_number())
  623. {
  624. slot->sparams.logit_bias[tok] = el[1].get<float>();
  625. }
  626. else if (el[1].is_boolean() && !el[1].get<bool>())
  627. {
  628. slot->sparams.logit_bias[tok] = -INFINITY;
  629. }
  630. }
  631. }
  632. }
  633. }
  634. slot->params.antiprompt.clear();
  635. const auto &stop = data.find("stop");
  636. if (stop != data.end() && stop->is_array())
  637. {
  638. for (const auto &word : *stop)
  639. {
  640. if (!word.empty())
  641. {
  642. slot->params.antiprompt.push_back(word);
  643. }
  644. }
  645. }
  646. if (multimodal)
  647. {
  648. const auto &images_data = data.find("image_data");
  649. if (images_data != data.end() && images_data->is_array())
  650. {
  651. for (const auto &img : *images_data)
  652. {
  653. std::string data_b64 = img["data"].get<std::string>();
  654. slot_image img_sl;
  655. img_sl.id = img.count("id") != 0 ? img["id"].get<int>() : slot->images.size();
  656. int width, height, channels;
  657. std::vector<uint8_t> image_buffer = base64_decode(data_b64);
  658. data_b64.clear();
  659. auto data = stbi_load_from_memory(image_buffer.data(), image_buffer.size(), &width, &height, &channels, 3);
  660. if (!data) {
  661. LOG_TEE("slot %i - failed to load image [id: %i]\n", slot->id, img_sl.id);
  662. return false;
  663. }
  664. LOG_TEE("slot %i - image loaded [id: %i] resolution (%i x %i)\n", slot->id, img_sl.id, width, height);
  665. img_sl.img_data.nx = width;
  666. img_sl.img_data.ny = height;
  667. img_sl.img_data.size = width * height * 3;
  668. img_sl.img_data.data = new uint8_t[width * height * 3]();
  669. memcpy(img_sl.img_data.data, data, width * height * 3);
  670. stbi_image_free(data);
  671. img_sl.request_encode_image = true;
  672. slot->images.push_back(img_sl);
  673. }
  674. // process prompt
  675. // example: system prompt [img-102] user [img-103] describe [img-134] -> [{id: 102, prefix: 'system prompt '}, {id: 103, prefix: ' user '}, {id: 134, prefix: ' describe '}]}
  676. if (slot->images.size() > 0 && !slot->prompt.is_array())
  677. {
  678. std::string prompt = slot->prompt.get<std::string>();
  679. size_t pos = 0, begin_prefix = 0;
  680. std::string pattern = "[img-";
  681. while ((pos = prompt.find(pattern, pos)) != std::string::npos) {
  682. size_t end_prefix = pos;
  683. pos += pattern.length();
  684. size_t end_pos = prompt.find("]", pos);
  685. if (end_pos != std::string::npos)
  686. {
  687. std::string image_id = prompt.substr(pos, end_pos - pos);
  688. try
  689. {
  690. int img_id = std::stoi(image_id);
  691. bool found = false;
  692. for (slot_image &img : slot->images)
  693. {
  694. if (img.id == img_id) {
  695. found = true;
  696. img.prefix_prompt = prompt.substr(begin_prefix, end_prefix - begin_prefix);
  697. begin_prefix = end_pos + 1;
  698. break;
  699. }
  700. }
  701. if (!found) {
  702. LOG_TEE("ERROR: Image with id: %i, not found.\n", img_id);
  703. slot->images.clear();
  704. return false;
  705. }
  706. } catch (const std::invalid_argument& e) {
  707. LOG_TEE("Invalid image number id in prompt\n");
  708. slot->images.clear();
  709. return false;
  710. }
  711. }
  712. }
  713. slot->prompt = "";
  714. slot->params.input_suffix = prompt.substr(begin_prefix);
  715. slot->params.cache_prompt = false; // multimodal doesn't support cache prompt
  716. }
  717. }
  718. }
  719. if (slot->ctx_sampling != nullptr)
  720. {
  721. llama_sampling_free(slot->ctx_sampling);
  722. }
  723. slot->ctx_sampling = llama_sampling_init(slot->sparams);
  724. slot->command = LOAD_PROMPT;
  725. all_slots_are_idle = false;
  726. LOG_TEE("slot %i is processing [task id: %i]\n", slot->id, slot->task_id);
  727. return true;
  728. }
  729. void kv_cache_clear() {
  730. // clear the entire KV cache
  731. llama_kv_cache_tokens_rm(ctx, -1, -1);
  732. clean_kv_cache = false;
  733. }
  734. void update_system_prompt() {
  735. system_tokens = ::llama_tokenize(ctx, system_prompt, true);
  736. llama_batch_clear(batch);
  737. kv_cache_clear();
  738. for (int i = 0; i < (int) system_tokens.size(); ++i)
  739. {
  740. llama_batch_add(batch, system_tokens[i], i, { 0 }, false);
  741. }
  742. if (llama_decode(ctx, batch) != 0)
  743. {
  744. LOG_TEE("%s: llama_decode() failed\n", __func__);
  745. return;
  746. }
  747. // assign the system KV cache to all parallel sequences
  748. for (int32_t i = 1; i < params.n_parallel; ++i)
  749. {
  750. llama_kv_cache_seq_cp(ctx, 0, i, 0, system_tokens.size());
  751. }
  752. LOG_TEE("system prompt updated\n");
  753. system_need_update = false;
  754. }
  755. void notify_system_prompt_changed() {
  756. // release all slots
  757. for (llama_client_slot &slot : slots)
  758. {
  759. slot.release();
  760. }
  761. system_need_update = true;
  762. }
  763. void process_system_prompt_data(const json &sys_props) {
  764. system_prompt = sys_props.value("prompt", "");
  765. name_user = sys_props.value("anti_prompt", "");
  766. name_assistant = sys_props.value("assistant_name", "");
  767. if (slots.size() > 0)
  768. {
  769. notify_system_prompt_changed();
  770. }
  771. }
  772. static size_t find_stopping_strings(const std::string &text, const size_t last_token_size,
  773. const stop_type type, llama_client_slot &slot)
  774. {
  775. size_t stop_pos = std::string::npos;
  776. for (const std::string &word : slot.params.antiprompt)
  777. {
  778. size_t pos;
  779. if (type == STOP_FULL)
  780. {
  781. const size_t tmp = word.size() + last_token_size;
  782. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  783. pos = text.find(word, from_pos);
  784. }
  785. else
  786. {
  787. pos = find_partial_stop_string(word, text);
  788. }
  789. if (pos != std::string::npos &&
  790. (stop_pos == std::string::npos || pos < stop_pos))
  791. {
  792. if (type == STOP_FULL)
  793. {
  794. slot.stopped_word = true;
  795. slot.stopping_word = word;
  796. slot.has_next_token = false;
  797. }
  798. stop_pos = pos;
  799. }
  800. }
  801. return stop_pos;
  802. }
  803. bool process_token(completion_token_output &result, llama_client_slot &slot) {
  804. // remember which tokens were sampled - used for repetition penalties during sampling
  805. const std::string token_str = llama_token_to_piece(ctx, result.tok);
  806. slot.sampled = result.tok;
  807. // search stop word and delete it
  808. slot.generated_text += token_str;
  809. slot.has_next_token = true;
  810. if (slot.multibyte_pending > 0)
  811. {
  812. slot.multibyte_pending -= token_str.size();
  813. }
  814. else if (token_str.size() == 1)
  815. {
  816. const char c = token_str[0];
  817. // 2-byte characters: 110xxxxx 10xxxxxx
  818. if ((c & 0xE0) == 0xC0)
  819. {
  820. slot.multibyte_pending = 1;
  821. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  822. }
  823. else if ((c & 0xF0) == 0xE0)
  824. {
  825. slot.multibyte_pending = 2;
  826. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  827. }
  828. else if ((c & 0xF8) == 0xF0)
  829. {
  830. slot.multibyte_pending = 3;
  831. }
  832. else
  833. {
  834. slot.multibyte_pending = 0;
  835. }
  836. }
  837. if (slot.multibyte_pending == 0)
  838. {
  839. size_t pos = std::min(slot.sent_count, slot.generated_text.size());
  840. const std::string str_test = slot.generated_text.substr(pos);
  841. bool is_stop_full = false;
  842. size_t stop_pos = find_stopping_strings(str_test, token_str.size(), STOP_FULL, slot);
  843. if (stop_pos != std::string::npos)
  844. {
  845. is_stop_full = true;
  846. slot.generated_text.erase(
  847. slot.generated_text.begin() + pos + stop_pos,
  848. slot.generated_text.end());
  849. pos = std::min(slot.sent_count, slot.generated_text.size());
  850. }
  851. else
  852. {
  853. is_stop_full = false;
  854. stop_pos = find_stopping_strings(str_test, token_str.size(), STOP_PARTIAL, slot);
  855. }
  856. // check if there is any token to predict
  857. if (stop_pos == std::string::npos || (!slot.has_next_token && !is_stop_full && stop_pos > 0))
  858. {
  859. // no send the stop word in the response
  860. result.text_to_send = slot.generated_text.substr(pos, std::string::npos);
  861. slot.sent_count += result.text_to_send.size();
  862. // add the token to slot queue and cache
  863. }
  864. slot.add_token_string(result);
  865. if (slot.params.stream)
  866. {
  867. send_partial_response(slot, result);
  868. }
  869. }
  870. if (slot.multibyte_pending > 0 && !slot.has_next_token)
  871. {
  872. slot.has_next_token = true;
  873. }
  874. // check the limits
  875. if (slot.n_decoded > 2 && slot.has_next_token && !slot.has_budget(params))
  876. {
  877. slot.stopped_limit = true;
  878. slot.has_next_token = false;
  879. }
  880. if (!slot.cache_tokens.empty() && result.tok == llama_token_eos(model))
  881. {
  882. slot.stopped_eos = true;
  883. slot.has_next_token = false;
  884. LOG_VERBOSE("eos token found", {});
  885. }
  886. LOG_VERBOSE("next token", {
  887. {"token", result.tok},
  888. {"token_text", tokens_to_output_formatted_string(ctx, result.tok)},
  889. {"has_next_token", slot.has_next_token},
  890. {"n_remain", slot.n_remaining},
  891. {"num_tokens_predicted", slot.n_decoded},
  892. {"stopped_eos", slot.stopped_eos},
  893. {"stopped_word", slot.stopped_word},
  894. {"stopped_limit", slot.stopped_limit},
  895. {"stopping_word", slot.stopping_word},
  896. });
  897. return slot.has_next_token; // continue
  898. }
  899. bool process_images(llama_client_slot &slot) const
  900. {
  901. for (slot_image &img : slot.images)
  902. {
  903. if (!img.request_encode_image)
  904. {
  905. continue;
  906. }
  907. clip_image_f32 img_res;
  908. if (!clip_image_preprocess(clp_ctx, &img.img_data, &img_res, /*pad2square =*/ true))
  909. {
  910. LOG_TEE("Error processing the given image");
  911. clip_free(clp_ctx);
  912. return false;
  913. }
  914. img.image_tokens = clip_n_patches(clp_ctx);
  915. img.image_embedding = (float *)malloc(clip_embd_nbytes(clp_ctx));
  916. if (!img.image_embedding)
  917. {
  918. LOG_TEE("Unable to allocate memory for image embeddings\n");
  919. clip_free(clp_ctx);
  920. return false;
  921. }
  922. LOG_TEE("slot %i - encoding image [id: %i]\n", slot.id, img.id);
  923. if (!clip_image_encode(clp_ctx, params.n_threads, &img_res, img.image_embedding))
  924. {
  925. LOG_TEE("Unable to encode image\n");
  926. return false;
  927. }
  928. img.request_encode_image = false;
  929. }
  930. return slot.images.size() > 0;
  931. }
  932. void send_error(int id, std::string error)
  933. {
  934. std::lock_guard<std::mutex> lock(mutex_results);
  935. task_result res;
  936. res.id = id;
  937. res.error = true;
  938. res.result_json = { { "content", error } };
  939. queue_results.push_back(res);
  940. }
  941. json get_model_props()
  942. {
  943. return get_formated_generation(slots[0]);
  944. }
  945. json get_formated_generation(llama_client_slot &slot)
  946. {
  947. const auto eos_bias = slot.sparams.logit_bias.find(llama_token_eos(model));
  948. const bool ignore_eos = eos_bias != slot.sparams.logit_bias.end() &&
  949. eos_bias->second < 0.0f && std::isinf(eos_bias->second);
  950. return json {
  951. {"n_ctx", slot.n_ctx},
  952. {"model", params.model_alias},
  953. {"seed", slot.params.seed},
  954. {"temp", slot.sparams.temp},
  955. {"top_k", slot.sparams.top_k},
  956. {"top_p", slot.sparams.top_p},
  957. {"tfs_z", slot.sparams.tfs_z},
  958. {"typical_p", slot.sparams.typical_p},
  959. {"repeat_last_n", slot.sparams.penalty_last_n},
  960. {"repeat_penalty", slot.sparams.penalty_repeat},
  961. {"presence_penalty", slot.sparams.penalty_present},
  962. {"frequency_penalty", slot.sparams.penalty_freq},
  963. {"mirostat", slot.sparams.mirostat},
  964. {"mirostat_tau", slot.sparams.mirostat_tau},
  965. {"mirostat_eta", slot.sparams.mirostat_eta},
  966. {"penalize_nl", slot.sparams.penalize_nl},
  967. {"stop", slot.params.antiprompt},
  968. {"n_predict", slot.params.n_predict},
  969. {"n_keep", params.n_keep},
  970. {"ignore_eos", ignore_eos},
  971. {"stream", slot.params.stream},
  972. {"logit_bias", slot.sparams.logit_bias},
  973. {"n_probs", slot.sparams.n_probs},
  974. {"grammar", slot.sparams.grammar},
  975. };
  976. }
  977. void send_partial_response(llama_client_slot &slot, completion_token_output tkn)
  978. {
  979. std::lock_guard<std::mutex> lock(mutex_results);
  980. task_result res;
  981. res.id = slot.task_id;
  982. res.error = false;
  983. res.stop = false;
  984. res.result_json = json
  985. {
  986. {"content", tkn.text_to_send},
  987. {"stop", false},
  988. {"slot_id", slot.id},
  989. {"multimodal", multimodal}
  990. };
  991. if (slot.sparams.n_probs > 0)
  992. {
  993. std::vector<completion_token_output> probs_output = {};
  994. const std::vector<llama_token> to_send_toks = llama_tokenize(ctx, tkn.text_to_send, false);
  995. size_t probs_pos = std::min(slot.sent_token_probs_index, slot.generated_token_probs.size());
  996. size_t probs_stop_pos = std::min(slot.sent_token_probs_index + to_send_toks.size(), slot.generated_token_probs.size());
  997. if (probs_pos < probs_stop_pos)
  998. {
  999. probs_output = std::vector<completion_token_output>(slot.generated_token_probs.begin() + probs_pos, slot.generated_token_probs.begin() + probs_stop_pos);
  1000. }
  1001. slot.sent_token_probs_index = probs_stop_pos;
  1002. res.result_json["completion_probabilities"] = probs_vector_to_json(ctx, probs_output);
  1003. }
  1004. queue_results.push_back(res);
  1005. }
  1006. void send_final_response(llama_client_slot &slot)
  1007. {
  1008. std::lock_guard<std::mutex> lock(mutex_results);
  1009. task_result res;
  1010. res.id = slot.task_id;
  1011. res.error = false;
  1012. res.stop = true;
  1013. res.result_json = json
  1014. {
  1015. {"content", !slot.params.stream ? slot.generated_text : ""},
  1016. {"slot_id", slot.id},
  1017. {"stop", true},
  1018. {"model", params.model_alias},
  1019. {"tokens_predicted", slot.n_decoded},
  1020. {"tokens_evaluated", slot.num_prompt_tokens},
  1021. {"generation_settings", get_formated_generation(slot)},
  1022. {"prompt", slot.prompt},
  1023. {"truncated", slot.truncated},
  1024. {"stopped_eos", slot.stopped_eos},
  1025. {"stopped_word", slot.stopped_word},
  1026. {"stopped_limit", slot.stopped_limit},
  1027. {"stopping_word", slot.stopping_word},
  1028. {"tokens_cached", slot.n_past},
  1029. {"timings", slot.get_formated_timings()}
  1030. };
  1031. if (slot.sparams.n_probs > 0)
  1032. {
  1033. std::vector<completion_token_output> probs = {};
  1034. if (!slot.params.stream && slot.stopped_word)
  1035. {
  1036. const std::vector<llama_token> stop_word_toks = llama_tokenize(ctx, slot.stopping_word, false);
  1037. probs = std::vector<completion_token_output>(slot.generated_token_probs.begin(), slot.generated_token_probs.end() - stop_word_toks.size());
  1038. }
  1039. else
  1040. {
  1041. probs = std::vector<completion_token_output>(
  1042. slot.generated_token_probs.begin(),
  1043. slot.generated_token_probs.begin() + slot.sent_token_probs_index);
  1044. }
  1045. res.result_json["completion_probabilities"] = probs_vector_to_json(ctx, probs);
  1046. }
  1047. queue_results.push_back(res);
  1048. }
  1049. void send_embedding(llama_client_slot &slot)
  1050. {
  1051. std::lock_guard<std::mutex> lock(mutex_results);
  1052. task_result res;
  1053. res.id = slot.task_id;
  1054. res.error = false;
  1055. res.stop = true;
  1056. const int n_embd = llama_n_embd(model);
  1057. if (!params.embedding)
  1058. {
  1059. LOG_WARNING("embedding disabled", {
  1060. {"params.embedding", params.embedding},
  1061. });
  1062. res.result_json = json
  1063. {
  1064. {"embedding", std::vector<float>(n_embd, 0.0f)},
  1065. };
  1066. }
  1067. else
  1068. {
  1069. const float *data = llama_get_embeddings(ctx);
  1070. std::vector<float> embedding(data, data + n_embd);
  1071. res.result_json = json
  1072. {
  1073. {"embedding", embedding },
  1074. };
  1075. }
  1076. queue_results.push_back(res);
  1077. }
  1078. int request_completion(json data, bool infill)
  1079. {
  1080. std::lock_guard<std::mutex> lock(mutex_tasks);
  1081. task_server task;
  1082. task.id = id_gen++;
  1083. task.data = data;
  1084. task.infill_mode = infill;
  1085. task.type = COMPLETION_TASK;
  1086. queue_tasks.push_back(task);
  1087. return task.id;
  1088. }
  1089. task_result next_result(int task_id)
  1090. {
  1091. while (true)
  1092. {
  1093. std::this_thread::sleep_for(std::chrono::microseconds(5));
  1094. std::lock_guard<std::mutex> lock(mutex_results);
  1095. if (queue_results.empty())
  1096. {
  1097. continue;
  1098. }
  1099. for (int i = 0; i < (int) queue_results.size(); i++)
  1100. {
  1101. if (queue_results[i].id == task_id)
  1102. {
  1103. task_result res = queue_results[i];
  1104. queue_results.erase(queue_results.begin() + i);
  1105. return res;
  1106. }
  1107. }
  1108. }
  1109. // never reached
  1110. //return task_result{-1, false, false, {}};
  1111. }
  1112. // for multiple images processing
  1113. bool ingest_images(llama_client_slot &slot, int n_batch)
  1114. {
  1115. int image_idx = 0;
  1116. while (image_idx < (int) slot.images.size())
  1117. {
  1118. slot_image &img = slot.images[image_idx];
  1119. // process prefix prompt
  1120. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch)
  1121. {
  1122. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  1123. llama_batch batch_view = {
  1124. n_tokens,
  1125. batch.token + i,
  1126. nullptr,
  1127. batch.pos + i,
  1128. batch.n_seq_id + i,
  1129. batch.seq_id + i,
  1130. batch.logits + i,
  1131. 0, 0, 0, // unused
  1132. };
  1133. if (llama_decode(ctx, batch_view))
  1134. {
  1135. LOG_TEE("%s : failed to eval\n", __func__);
  1136. return false;
  1137. }
  1138. }
  1139. // process image with llm
  1140. for (int i = 0; i < img.image_tokens; i += n_batch)
  1141. {
  1142. int n_eval = img.image_tokens - i;
  1143. if (n_eval > n_batch)
  1144. {
  1145. n_eval = n_batch;
  1146. }
  1147. const int n_embd = llama_n_embd(model);
  1148. llama_batch batch_img = { n_eval, nullptr, (img.image_embedding + i * n_embd), nullptr, nullptr, nullptr, nullptr, slot.n_past, 1, 0, };
  1149. if (llama_decode(ctx, batch_img))
  1150. {
  1151. LOG_TEE("%s : failed to eval image\n", __func__);
  1152. return false;
  1153. }
  1154. slot.n_past += n_eval;
  1155. }
  1156. image_idx++;
  1157. llama_batch_clear(batch);
  1158. // append prefix of next image
  1159. const auto json_prompt = (image_idx >= (int) slot.images.size()) ?
  1160. slot.params.input_suffix : // no more images, then process suffix prompt
  1161. (json)(slot.images[image_idx].prefix_prompt);
  1162. std::vector<llama_token> append_tokens = tokenize(json_prompt, false); // has next image
  1163. for (int i = 0; i < (int) append_tokens.size(); ++i)
  1164. {
  1165. llama_batch_add(batch, append_tokens[i], slot.n_past, { slot.id }, true);
  1166. slot.n_past += 1;
  1167. }
  1168. }
  1169. return true;
  1170. }
  1171. void request_cancel(int task_id)
  1172. {
  1173. std::lock_guard<std::mutex> lock(mutex_tasks);
  1174. task_server task;
  1175. task.id = id_gen++;
  1176. task.type = CANCEL_TASK;
  1177. task.target_id = task_id;
  1178. queue_tasks.push_back(task);
  1179. }
  1180. void process_tasks()
  1181. {
  1182. std::lock_guard<std::mutex> lock(mutex_tasks);
  1183. while (!queue_tasks.empty())
  1184. {
  1185. task_server task = queue_tasks.front();
  1186. queue_tasks.erase(queue_tasks.begin());
  1187. switch (task.type)
  1188. {
  1189. case COMPLETION_TASK: {
  1190. llama_client_slot *slot = get_slot(json_value(task.data, "slot_id", -1));
  1191. if (slot == nullptr)
  1192. {
  1193. LOG_TEE("slot unavailable\n");
  1194. // send error result
  1195. send_error(task.id, "slot unavaliable");
  1196. return;
  1197. }
  1198. if (task.data.contains("system_prompt"))
  1199. {
  1200. process_system_prompt_data(task.data["system_prompt"]);
  1201. }
  1202. slot->reset();
  1203. slot->infill = task.infill_mode;
  1204. slot->task_id = task.id;
  1205. if (!launch_slot_with_data(slot, task.data))
  1206. {
  1207. // send error result
  1208. send_error(task.id, "internal_error");
  1209. break;
  1210. }
  1211. } break;
  1212. case CANCEL_TASK: { // release slot linked with the task id
  1213. for (auto & slot : slots)
  1214. {
  1215. if (slot.task_id == task.target_id)
  1216. {
  1217. slot.release();
  1218. break;
  1219. }
  1220. }
  1221. } break;
  1222. }
  1223. }
  1224. }
  1225. bool update_slots() {
  1226. // attend tasks
  1227. process_tasks();
  1228. // update the system prompt wait until all slots are idle state
  1229. if (system_need_update && all_slots_are_idle)
  1230. {
  1231. LOG_TEE("updating system prompt\n");
  1232. update_system_prompt();
  1233. }
  1234. llama_batch_clear(batch);
  1235. if (all_slots_are_idle)
  1236. {
  1237. if (system_prompt.empty() && clean_kv_cache)
  1238. {
  1239. LOG_TEE("all slots are idle and system prompt is empty, clear the KV cache\n");
  1240. kv_cache_clear();
  1241. }
  1242. // avoid 100% usage of cpu all time
  1243. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  1244. }
  1245. for (llama_client_slot &slot : slots)
  1246. {
  1247. if (slot.is_processing() && slot.cache_tokens.size() >= (size_t) slot.n_ctx)
  1248. {
  1249. // Shift context
  1250. const int n_left = slot.n_past - slot.params.n_keep - 1;
  1251. const int n_discard = n_left / 2;
  1252. 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);
  1253. llama_kv_cache_seq_rm (ctx, slot.id, slot.params.n_keep + 1 , slot.params.n_keep + n_discard + 1);
  1254. llama_kv_cache_seq_shift(ctx, slot.id, slot.params.n_keep + 1 + n_discard, slot.n_past, -n_discard);
  1255. for (size_t i = slot.params.n_keep + 1 + n_discard; i < slot.cache_tokens.size(); i++)
  1256. {
  1257. slot.cache_tokens[i - n_discard] = slot.cache_tokens[i];
  1258. }
  1259. slot.cache_tokens.resize(slot.cache_tokens.size() - n_discard);
  1260. slot.n_past -= n_discard;
  1261. slot.truncated = true;
  1262. LOG_VERBOSE("context shift", {
  1263. {"n_ctx", n_ctx},
  1264. {"n_keep", params.n_keep},
  1265. {"n_left", n_left},
  1266. });
  1267. }
  1268. }
  1269. // decode any currently ongoing sequences
  1270. for (auto & slot : slots)
  1271. {
  1272. // release the slot
  1273. if (slot.command == RELEASE)
  1274. {
  1275. slot.state = IDLE;
  1276. slot.command = NONE;
  1277. slot.t_last_used = ggml_time_us();
  1278. LOG_TEE("slot %d released (%d tokens in cache)\n", slot.id, (int) slot.cache_tokens.size());
  1279. continue;
  1280. }
  1281. if (slot.state == IDLE)
  1282. {
  1283. continue;
  1284. }
  1285. slot.i_batch = batch.n_tokens;
  1286. llama_batch_add(batch, slot.sampled, system_tokens.size() + slot.n_past, { slot.id }, true);
  1287. slot.n_decoded += 1;
  1288. slot.n_past += 1;
  1289. }
  1290. // process in chunks of params.n_batch
  1291. int32_t n_batch = params.n_batch;
  1292. // assign workload to the slots
  1293. if (params.cont_batching || batch.n_tokens == 0)
  1294. {
  1295. for (auto & slot : slots)
  1296. {
  1297. const bool has_prompt = slot.prompt.is_array() || (slot.prompt.is_string() && !slot.prompt.get<std::string>().empty());
  1298. // empty prompt passed -> release the slot and send empty response
  1299. if (slot.state == IDLE && slot.command == LOAD_PROMPT && !has_prompt)
  1300. {
  1301. slot.release();
  1302. slot.print_timings();
  1303. send_final_response(slot);
  1304. continue;
  1305. }
  1306. // need process the prompt
  1307. if (slot.state == IDLE && slot.command == LOAD_PROMPT)
  1308. {
  1309. slot.state = PROCESSING;
  1310. slot.command = NONE;
  1311. std::vector<llama_token> prompt_tokens;
  1312. slot.t_start_process_prompt = ggml_time_us();
  1313. slot.t_start_genereration = 0;
  1314. if (slot.infill)
  1315. {
  1316. bool suff_rm_leading_spc = true;
  1317. if (params.input_suffix.find_first_of(' ') == 0 && params.input_suffix.size() > 1)
  1318. {
  1319. params.input_suffix.erase(0, 1);
  1320. suff_rm_leading_spc = false;
  1321. }
  1322. auto prefix_tokens = tokenize(slot.params.input_prefix, false);
  1323. auto suffix_tokens = tokenize(slot.params.input_suffix, false);
  1324. const int space_token = 29871; // TODO: this should not be hardcoded
  1325. if (suff_rm_leading_spc && !suffix_tokens.empty() && suffix_tokens[0] == space_token) {
  1326. suffix_tokens.erase(suffix_tokens.begin());
  1327. }
  1328. prefix_tokens.insert(prefix_tokens.begin(), llama_token_prefix(model));
  1329. prefix_tokens.insert(prefix_tokens.begin(), llama_token_bos(model)); // always add BOS
  1330. prefix_tokens.insert(prefix_tokens.end(), llama_token_suffix(model));
  1331. prefix_tokens.insert(prefix_tokens.end(), suffix_tokens.begin(), suffix_tokens.end());
  1332. prefix_tokens.push_back(llama_token_middle(model));
  1333. prompt_tokens = prefix_tokens;
  1334. }
  1335. else
  1336. {
  1337. prompt_tokens = tokenize(slot.prompt, system_prompt.empty()); // add BOS if there isn't system prompt
  1338. }
  1339. slot.num_prompt_tokens = prompt_tokens.size();
  1340. if (!slot.params.cache_prompt)
  1341. {
  1342. llama_sampling_reset(slot.ctx_sampling);
  1343. slot.n_past = 0;
  1344. slot.num_prompt_tokens_processed = slot.num_prompt_tokens;
  1345. }
  1346. else
  1347. {
  1348. if (slot.params.n_keep < 0)
  1349. {
  1350. slot.params.n_keep = slot.num_prompt_tokens;
  1351. }
  1352. slot.params.n_keep = std::min(slot.n_ctx - 4, slot.params.n_keep);
  1353. // if input prompt is too big, truncate it
  1354. if (slot.num_prompt_tokens >= slot.n_ctx)
  1355. {
  1356. const int n_left = slot.n_ctx - slot.params.n_keep;
  1357. const int n_block_size = n_left / 2;
  1358. const int erased_blocks = (slot.num_prompt_tokens - slot.params.n_keep - n_block_size) / n_block_size;
  1359. std::vector<llama_token> new_tokens(prompt_tokens.begin(), prompt_tokens.begin() + slot.params.n_keep);
  1360. new_tokens.insert(new_tokens.end(), prompt_tokens.begin() + slot.params.n_keep + erased_blocks * n_block_size, prompt_tokens.end());
  1361. LOG_VERBOSE("input truncated", {
  1362. {"n_ctx", slot.n_ctx},
  1363. {"n_keep", slot.params.n_keep},
  1364. {"n_left", n_left},
  1365. {"new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend())},
  1366. });
  1367. slot.truncated = true;
  1368. prompt_tokens = new_tokens;
  1369. slot.num_prompt_tokens = prompt_tokens.size();
  1370. GGML_ASSERT(slot.num_prompt_tokens < slot.n_ctx);
  1371. }
  1372. // push the prompt into the sampling context (do not apply grammar)
  1373. for (auto &token : prompt_tokens)
  1374. {
  1375. llama_sampling_accept(slot.ctx_sampling, ctx, token, false);
  1376. }
  1377. slot.n_past = common_part(slot.cache_tokens, prompt_tokens);
  1378. slot.num_prompt_tokens_processed = slot.num_prompt_tokens - slot.n_past;
  1379. LOG_TEE("slot %d : in cache: %i tokens | to process: %i tokens\n", slot.id, slot.n_past, slot.num_prompt_tokens_processed);
  1380. }
  1381. LOG_TEE("slot %d : kv cache rm - [%d, end)\n", slot.id, (int) system_tokens.size() + slot.n_past);
  1382. llama_kv_cache_seq_rm(ctx, slot.id, system_tokens.size() + slot.n_past, -1);
  1383. slot.cache_tokens = prompt_tokens;
  1384. if (slot.n_past == slot.num_prompt_tokens)
  1385. {
  1386. // we have to evaluate at least 1 token to generate logits.
  1387. LOG_TEE("slot %d : we have to evaluate at least 1 token to generate logits\n", slot.id);
  1388. slot.n_past--;
  1389. }
  1390. LOG_VERBOSE("prompt ingested", {
  1391. {"n_past", slot.n_past},
  1392. {"cached", tokens_to_str(ctx, slot.cache_tokens.cbegin(), slot.cache_tokens.cbegin() + slot.n_past)},
  1393. {"to_eval", tokens_to_str(ctx, slot.cache_tokens.cbegin() + slot.n_past, slot.cache_tokens.cend())},
  1394. });
  1395. const bool has_images = process_images(slot);
  1396. // process the prefix of first image
  1397. std::vector<llama_token> prefix_tokens = has_images ? tokenize(slot.images[0].prefix_prompt, true) : prompt_tokens;
  1398. for (; slot.n_past < (int) prefix_tokens.size(); ++slot.n_past)
  1399. {
  1400. llama_batch_add(batch, prefix_tokens[slot.n_past], system_tokens.size() + slot.n_past, { slot.id }, false);
  1401. }
  1402. if (has_images && !ingest_images(slot, n_batch))
  1403. {
  1404. LOG_TEE("failed processing images\n");
  1405. return false;
  1406. }
  1407. // extract the logits only for the last token
  1408. if (batch.n_tokens > 0)
  1409. {
  1410. batch.logits[batch.n_tokens - 1] = true;
  1411. }
  1412. slot.n_decoded = 0;
  1413. slot.i_batch = batch.n_tokens - 1;
  1414. }
  1415. }
  1416. }
  1417. if (batch.n_tokens == 0)
  1418. {
  1419. all_slots_are_idle = true;
  1420. return true;
  1421. }
  1422. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch)
  1423. {
  1424. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  1425. llama_batch batch_view =
  1426. {
  1427. n_tokens,
  1428. batch.token + i,
  1429. nullptr,
  1430. batch.pos + i,
  1431. batch.n_seq_id + i,
  1432. batch.seq_id + i,
  1433. batch.logits + i,
  1434. 0, 0, 0, // unused
  1435. };
  1436. const int ret = llama_decode(ctx, batch_view);
  1437. if (ret != 0)
  1438. {
  1439. if (n_batch == 1 || ret < 0)
  1440. {
  1441. // if you get here, it means the KV cache is full - try increasing it via the context size
  1442. LOG_TEE("%s : failed to decode the batch, n_batch = %d, ret = %d\n", __func__, n_batch, ret);
  1443. return false;
  1444. }
  1445. LOG_TEE("%s : failed to find free space in the KV cache, retrying with smaller n_batch = %d\n", __func__, n_batch / 2);
  1446. // retry with half the batch size to try to find a free slot in the KV cache
  1447. n_batch /= 2;
  1448. i -= n_batch;
  1449. continue;
  1450. }
  1451. for (auto & slot : slots)
  1452. {
  1453. if (slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens))
  1454. {
  1455. continue;
  1456. }
  1457. // prompt evaluated for embedding
  1458. if (params.embedding)
  1459. {
  1460. send_embedding(slot);
  1461. slot.release();
  1462. slot.i_batch = -1;
  1463. return true;
  1464. }
  1465. completion_token_output result;
  1466. const llama_token id = llama_sampling_sample(slot.ctx_sampling, ctx, NULL, slot.i_batch - i);
  1467. llama_sampling_accept(slot.ctx_sampling, ctx, id, true);
  1468. if (slot.n_decoded == 1)
  1469. {
  1470. slot.t_start_genereration = ggml_time_us();
  1471. slot.t_prompt_processing = (slot.t_start_genereration - slot.t_start_process_prompt) / 1e3;
  1472. }
  1473. llama_token_data_array cur_p = { slot.ctx_sampling->cur.data(), slot.ctx_sampling->cur.size(), false };
  1474. result.tok = id;
  1475. const int32_t n_probs = slot.sparams.n_probs;
  1476. if (slot.sparams.temp <= 0 && n_probs > 0)
  1477. {
  1478. // for llama_sample_token_greedy we need to sort candidates
  1479. llama_sample_softmax(ctx, &cur_p);
  1480. }
  1481. for (size_t i = 0; i < std::min(cur_p.size, (size_t)n_probs); ++i)
  1482. {
  1483. result.probs.push_back({cur_p.data[i].id, cur_p.data[i].p});
  1484. }
  1485. if (!process_token(result, slot))
  1486. {
  1487. slot.release();
  1488. slot.print_timings();
  1489. send_final_response(slot);
  1490. }
  1491. slot.i_batch = -1;
  1492. }
  1493. }
  1494. return true;
  1495. }
  1496. };
  1497. static void server_print_usage(const char *argv0, const gpt_params &params,
  1498. const server_params &sparams)
  1499. {
  1500. printf("usage: %s [options]\n", argv0);
  1501. printf("\n");
  1502. printf("options:\n");
  1503. printf(" -h, --help show this help message and exit\n");
  1504. printf(" -v, --verbose verbose output (default: %s)\n", server_verbose ? "enabled" : "disabled");
  1505. printf(" -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  1506. printf(" -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  1507. printf(" --rope-freq-base N RoPE base frequency (default: loaded from model)\n");
  1508. printf(" --rope-freq-scale N RoPE frequency scaling factor (default: loaded from model)\n");
  1509. printf(" -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  1510. printf(" --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  1511. printf(" not recommended: doubles context memory required and no measurable increase in quality\n");
  1512. if (llama_mlock_supported())
  1513. {
  1514. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  1515. }
  1516. if (llama_mmap_supported())
  1517. {
  1518. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  1519. }
  1520. printf(" --numa attempt optimizations that help on some NUMA systems\n");
  1521. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  1522. printf(" -ngl N, --n-gpu-layers N\n");
  1523. printf(" number of layers to store in VRAM\n");
  1524. printf(" -ts SPLIT --tensor-split SPLIT\n");
  1525. printf(" how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  1526. printf(" -mg i, --main-gpu i the GPU to use for scratch and small tensors\n");
  1527. printf(" -nommq, --no-mul-mat-q\n");
  1528. printf(" use cuBLAS instead of custom mul_mat_q CUDA kernels.\n");
  1529. printf(" Not recommended since this is both slower and uses more VRAM.\n");
  1530. #endif
  1531. printf(" -m FNAME, --model FNAME\n");
  1532. printf(" model path (default: %s)\n", params.model.c_str());
  1533. printf(" -a ALIAS, --alias ALIAS\n");
  1534. printf(" set an alias for the model, will be added as `model` field in completion response\n");
  1535. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  1536. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  1537. printf(" --host ip address to listen (default (default: %s)\n", sparams.hostname.c_str());
  1538. printf(" --port PORT port to listen (default (default: %d)\n", sparams.port);
  1539. printf(" --path PUBLIC_PATH path from which to serve static files (default %s)\n", sparams.public_path.c_str());
  1540. printf(" -to N, --timeout N server read/write timeout in seconds (default: %d)\n", sparams.read_timeout);
  1541. printf(" --embedding enable embedding vector output (default: %s)\n", params.embedding ? "enabled" : "disabled");
  1542. printf(" -np N, --parallel N number of slots for process requests (default: %d)\n", params.n_parallel);
  1543. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)\n");
  1544. printf(" -spf FNAME, --system-prompt-file FNAME\n");
  1545. printf(" Set a file to load a system prompt (initial prompt of all slots), this is useful for chat applications.\n");
  1546. printf(" --mmproj MMPROJ_FILE path to a multimodal projector file for LLaVA.\n");
  1547. printf("\n");
  1548. }
  1549. static void server_params_parse(int argc, char **argv, server_params &sparams,
  1550. gpt_params &params, llama_server_context& llama)
  1551. {
  1552. gpt_params default_params;
  1553. server_params default_sparams;
  1554. std::string arg;
  1555. bool invalid_param = false;
  1556. for (int i = 1; i < argc; i++)
  1557. {
  1558. arg = argv[i];
  1559. if (arg == "--port")
  1560. {
  1561. if (++i >= argc)
  1562. {
  1563. invalid_param = true;
  1564. break;
  1565. }
  1566. sparams.port = std::stoi(argv[i]);
  1567. }
  1568. else if (arg == "--host")
  1569. {
  1570. if (++i >= argc)
  1571. {
  1572. invalid_param = true;
  1573. break;
  1574. }
  1575. sparams.hostname = argv[i];
  1576. }
  1577. else if (arg == "--path")
  1578. {
  1579. if (++i >= argc)
  1580. {
  1581. invalid_param = true;
  1582. break;
  1583. }
  1584. sparams.public_path = argv[i];
  1585. }
  1586. else if (arg == "--timeout" || arg == "-to")
  1587. {
  1588. if (++i >= argc)
  1589. {
  1590. invalid_param = true;
  1591. break;
  1592. }
  1593. sparams.read_timeout = std::stoi(argv[i]);
  1594. sparams.write_timeout = std::stoi(argv[i]);
  1595. }
  1596. else if (arg == "-m" || arg == "--model")
  1597. {
  1598. if (++i >= argc)
  1599. {
  1600. invalid_param = true;
  1601. break;
  1602. }
  1603. params.model = argv[i];
  1604. }
  1605. else if (arg == "-a" || arg == "--alias")
  1606. {
  1607. if (++i >= argc)
  1608. {
  1609. invalid_param = true;
  1610. break;
  1611. }
  1612. params.model_alias = argv[i];
  1613. }
  1614. else if (arg == "-h" || arg == "--help")
  1615. {
  1616. server_print_usage(argv[0], default_params, default_sparams);
  1617. exit(0);
  1618. }
  1619. else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size")
  1620. {
  1621. if (++i >= argc)
  1622. {
  1623. invalid_param = true;
  1624. break;
  1625. }
  1626. params.n_ctx = std::stoi(argv[i]);
  1627. }
  1628. else if (arg == "--rope-freq-base")
  1629. {
  1630. if (++i >= argc)
  1631. {
  1632. invalid_param = true;
  1633. break;
  1634. }
  1635. params.rope_freq_base = std::stof(argv[i]);
  1636. }
  1637. else if (arg == "--rope-freq-scale")
  1638. {
  1639. if (++i >= argc)
  1640. {
  1641. invalid_param = true;
  1642. break;
  1643. }
  1644. params.rope_freq_scale = std::stof(argv[i]);
  1645. }
  1646. else if (arg == "--memory-f32" || arg == "--memory_f32")
  1647. {
  1648. params.memory_f16 = false;
  1649. }
  1650. else if (arg == "--threads" || arg == "-t")
  1651. {
  1652. if (++i >= argc)
  1653. {
  1654. invalid_param = true;
  1655. break;
  1656. }
  1657. params.n_threads = std::stoi(argv[i]);
  1658. }
  1659. else if (arg == "-b" || arg == "--batch-size")
  1660. {
  1661. if (++i >= argc)
  1662. {
  1663. invalid_param = true;
  1664. break;
  1665. }
  1666. params.n_batch = std::stoi(argv[i]);
  1667. params.n_batch = std::min(512, params.n_batch);
  1668. }
  1669. else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers")
  1670. {
  1671. if (++i >= argc)
  1672. {
  1673. invalid_param = true;
  1674. break;
  1675. }
  1676. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  1677. params.n_gpu_layers = std::stoi(argv[i]);
  1678. #else
  1679. LOG_WARNING("Not compiled with GPU offload support, --n-gpu-layers option will be ignored. "
  1680. "See main README.md for information on enabling GPU BLAS support",
  1681. {{"n_gpu_layers", params.n_gpu_layers}});
  1682. #endif
  1683. }
  1684. else if (arg == "--tensor-split" || arg == "-ts")
  1685. {
  1686. if (++i >= argc)
  1687. {
  1688. invalid_param = true;
  1689. break;
  1690. }
  1691. #ifdef GGML_USE_CUBLAS
  1692. std::string arg_next = argv[i];
  1693. // split string by , and /
  1694. const std::regex regex{R"([,/]+)"};
  1695. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  1696. std::vector<std::string> split_arg{it, {}};
  1697. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  1698. for (size_t i_device = 0; i_device < LLAMA_MAX_DEVICES; ++i_device)
  1699. {
  1700. if (i_device < split_arg.size())
  1701. {
  1702. params.tensor_split[i_device] = std::stof(split_arg[i_device]);
  1703. }
  1704. else
  1705. {
  1706. params.tensor_split[i_device] = 0.0f;
  1707. }
  1708. }
  1709. #else
  1710. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n", {});
  1711. #endif // GGML_USE_CUBLAS
  1712. }
  1713. else if (arg == "--no-mul-mat-q" || arg == "-nommq")
  1714. {
  1715. #ifdef GGML_USE_CUBLAS
  1716. params.mul_mat_q = false;
  1717. #else
  1718. LOG_WARNING("warning: llama.cpp was compiled without cuBLAS. Disabling mul_mat_q kernels has no effect.\n", {});
  1719. #endif // GGML_USE_CUBLAS
  1720. }
  1721. else if (arg == "--main-gpu" || arg == "-mg")
  1722. {
  1723. if (++i >= argc)
  1724. {
  1725. invalid_param = true;
  1726. break;
  1727. }
  1728. #ifdef GGML_USE_CUBLAS
  1729. params.main_gpu = std::stoi(argv[i]);
  1730. #else
  1731. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.", {});
  1732. #endif
  1733. }
  1734. else if (arg == "--lora")
  1735. {
  1736. if (++i >= argc)
  1737. {
  1738. invalid_param = true;
  1739. break;
  1740. }
  1741. params.lora_adapter.push_back(std::make_tuple(argv[i], 1.0f));
  1742. params.use_mmap = false;
  1743. }
  1744. else if (arg == "--lora-scaled")
  1745. {
  1746. if (++i >= argc)
  1747. {
  1748. invalid_param = true;
  1749. break;
  1750. }
  1751. const char * lora_adapter = argv[i];
  1752. if (++i >= argc)
  1753. {
  1754. invalid_param = true;
  1755. break;
  1756. }
  1757. params.lora_adapter.push_back(std::make_tuple(lora_adapter, std::stof(argv[i])));
  1758. params.use_mmap = false;
  1759. }
  1760. else if (arg == "--lora-base")
  1761. {
  1762. if (++i >= argc)
  1763. {
  1764. invalid_param = true;
  1765. break;
  1766. }
  1767. params.lora_base = argv[i];
  1768. }
  1769. else if (arg == "-v" || arg == "--verbose")
  1770. {
  1771. #if SERVER_VERBOSE != 1
  1772. LOG_WARNING("server.cpp is not built with verbose logging.", {});
  1773. #else
  1774. server_verbose = true;
  1775. #endif
  1776. }
  1777. else if (arg == "--mlock")
  1778. {
  1779. params.use_mlock = true;
  1780. }
  1781. else if (arg == "--no-mmap")
  1782. {
  1783. params.use_mmap = false;
  1784. }
  1785. else if (arg == "--numa")
  1786. {
  1787. params.numa = true;
  1788. }
  1789. else if (arg == "--embedding")
  1790. {
  1791. params.embedding = true;
  1792. }
  1793. else if (arg == "-cb" || arg == "--cont-batching")
  1794. {
  1795. params.cont_batching = true;
  1796. }
  1797. else if (arg == "-np" || arg == "--parallel")
  1798. {
  1799. if (++i >= argc)
  1800. {
  1801. invalid_param = true;
  1802. break;
  1803. }
  1804. params.n_parallel = std::stoi(argv[i]);
  1805. } else if (arg == "-n" || arg == "--n-predict")
  1806. {
  1807. if (++i >= argc)
  1808. {
  1809. invalid_param = true;
  1810. break;
  1811. }
  1812. params.n_predict = std::stoi(argv[i]);
  1813. } else if (arg == "-spf" || arg == "--system-prompt-file")
  1814. {
  1815. if (++i >= argc)
  1816. {
  1817. invalid_param = true;
  1818. break;
  1819. }
  1820. std::ifstream file(argv[i]);
  1821. if (!file) {
  1822. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1823. invalid_param = true;
  1824. break;
  1825. }
  1826. std::string systm_content;
  1827. std::copy(
  1828. std::istreambuf_iterator<char>(file),
  1829. std::istreambuf_iterator<char>(),
  1830. std::back_inserter(systm_content)
  1831. );
  1832. llama.process_system_prompt_data(json::parse(systm_content));
  1833. }
  1834. else if(arg == "--mmproj")
  1835. {
  1836. if (++i >= argc)
  1837. {
  1838. invalid_param = true;
  1839. break;
  1840. }
  1841. params.mmproj = argv[i];
  1842. }
  1843. else
  1844. {
  1845. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  1846. server_print_usage(argv[0], default_params, default_sparams);
  1847. exit(1);
  1848. }
  1849. }
  1850. if (invalid_param)
  1851. {
  1852. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  1853. server_print_usage(argv[0], default_params, default_sparams);
  1854. exit(1);
  1855. }
  1856. }
  1857. static json format_partial_response(
  1858. llama_server_context &llama, llama_client_slot *slot, const std::string &content, const std::vector<completion_token_output> &probs
  1859. ) {
  1860. json res = json
  1861. {
  1862. {"content", content },
  1863. {"stop", false},
  1864. {"slot_id", slot->id },
  1865. {"multimodal", llama.multimodal }
  1866. };
  1867. if (slot->sparams.n_probs > 0)
  1868. {
  1869. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  1870. }
  1871. return res;
  1872. }
  1873. static json format_tokenizer_response(const std::vector<llama_token> &tokens)
  1874. {
  1875. return json{
  1876. {"tokens", tokens}};
  1877. }
  1878. static json format_detokenized_response(std::string content)
  1879. {
  1880. return json{
  1881. {"content", content}};
  1882. }
  1883. static void log_server_request(const httplib::Request &req, const httplib::Response &res)
  1884. {
  1885. LOG_INFO("request", {
  1886. {"remote_addr", req.remote_addr},
  1887. {"remote_port", req.remote_port},
  1888. {"status", res.status},
  1889. {"method", req.method},
  1890. {"path", req.path},
  1891. {"params", req.params},
  1892. });
  1893. LOG_VERBOSE("request", {
  1894. {"request", req.body},
  1895. {"response", res.body},
  1896. });
  1897. }
  1898. struct token_translator
  1899. {
  1900. llama_context * ctx;
  1901. std::string operator()(llama_token tok) const { return llama_token_to_piece(ctx, tok); }
  1902. std::string operator()(const completion_token_output &cto) const { return (*this)(cto.tok); }
  1903. };
  1904. static void append_to_generated_text_from_generated_token_probs(llama_server_context &llama, llama_client_slot *slot)
  1905. {
  1906. auto & gtps = slot->generated_token_probs;
  1907. auto translator = token_translator{llama.ctx};
  1908. auto add_strlen = [=](size_t sum, const completion_token_output & cto) { return sum + translator(cto).size(); };
  1909. const size_t len = std::accumulate(gtps.begin(), gtps.end(), size_t(0), add_strlen);
  1910. if (slot->generated_text.capacity() < slot->generated_text.size() + len)
  1911. {
  1912. slot->generated_text.reserve(slot->generated_text.size() + len);
  1913. }
  1914. for (const completion_token_output & cto : gtps)
  1915. {
  1916. slot->generated_text += translator(cto);
  1917. }
  1918. }
  1919. int main(int argc, char **argv)
  1920. {
  1921. // own arguments required by this example
  1922. gpt_params params;
  1923. server_params sparams;
  1924. // struct that contains llama context and inference
  1925. llama_server_context llama;
  1926. server_params_parse(argc, argv, sparams, params, llama);
  1927. if (params.model_alias == "unknown")
  1928. {
  1929. params.model_alias = params.model;
  1930. }
  1931. llama_backend_init(params.numa);
  1932. LOG_INFO("build info", {{"build", BUILD_NUMBER},
  1933. {"commit", BUILD_COMMIT}});
  1934. LOG_INFO("system info", {
  1935. {"n_threads", params.n_threads},
  1936. {"n_threads_batch", params.n_threads_batch},
  1937. {"total_threads", std::thread::hardware_concurrency()},
  1938. {"system_info", llama_print_system_info()},
  1939. });
  1940. // load the model
  1941. if (!llama.load_model(params))
  1942. {
  1943. return 1;
  1944. }
  1945. llama.initialize();
  1946. httplib::Server svr;
  1947. svr.set_default_headers({{"Server", "llama.cpp"},
  1948. {"Access-Control-Allow-Origin", "*"},
  1949. {"Access-Control-Allow-Headers", "content-type"}});
  1950. // this is only called if no index.html is found in the public --path
  1951. svr.Get("/", [](const httplib::Request &, httplib::Response &res)
  1952. {
  1953. res.set_content(reinterpret_cast<const char*>(&index_html), index_html_len, "text/html");
  1954. return false;
  1955. });
  1956. // this is only called if no index.js is found in the public --path
  1957. svr.Get("/index.js", [](const httplib::Request &, httplib::Response &res)
  1958. {
  1959. res.set_content(reinterpret_cast<const char *>(&index_js), index_js_len, "text/javascript");
  1960. return false;
  1961. });
  1962. // this is only called if no index.html is found in the public --path
  1963. svr.Get("/completion.js", [](const httplib::Request &, httplib::Response &res)
  1964. {
  1965. res.set_content(reinterpret_cast<const char*>(&completion_js), completion_js_len, "application/javascript");
  1966. return false;
  1967. });
  1968. // this is only called if no index.html is found in the public --path
  1969. svr.Get("/json-schema-to-grammar.mjs", [](const httplib::Request &, httplib::Response &res)
  1970. {
  1971. res.set_content(reinterpret_cast<const char*>(&json_schema_to_grammar_mjs), json_schema_to_grammar_mjs_len, "application/javascript");
  1972. return false;
  1973. });
  1974. svr.Get("/props", [&llama](const httplib::Request & /*req*/, httplib::Response &res)
  1975. {
  1976. res.set_header("Access-Control-Allow-Origin", "*");
  1977. json data = {
  1978. { "user_name", llama.name_user.c_str() },
  1979. { "assistant_name", llama.name_assistant.c_str() }
  1980. };
  1981. res.set_content(data.dump(), "application/json");
  1982. });
  1983. svr.Post("/completion", [&llama](const httplib::Request &req, httplib::Response &res)
  1984. {
  1985. json data = json::parse(req.body);
  1986. const int task_id = llama.request_completion(data, false);
  1987. if (!json_value(data, "stream", false)) {
  1988. std::string completion_text;
  1989. task_result result = llama.next_result(task_id);
  1990. if (!result.error && result.stop) {
  1991. res.set_content(result.result_json.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
  1992. }
  1993. else
  1994. {
  1995. res.status = 404;
  1996. res.set_content(result.result_json["content"], "text/plain");
  1997. return;
  1998. }
  1999. } else {
  2000. const auto chunked_content_provider = [task_id, &llama](size_t, httplib::DataSink & sink)
  2001. {
  2002. while (true)
  2003. {
  2004. task_result result = llama.next_result(task_id);
  2005. if (!result.error) {
  2006. const std::string str =
  2007. "data: " +
  2008. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace) +
  2009. "\n\n";
  2010. LOG_VERBOSE("data stream", {
  2011. { "to_send", str }
  2012. });
  2013. if (!sink.write(str.c_str(), str.size()))
  2014. {
  2015. return false;
  2016. }
  2017. if (result.stop) {
  2018. break;
  2019. }
  2020. } else {
  2021. break;
  2022. }
  2023. }
  2024. sink.done();
  2025. return true;
  2026. };
  2027. auto on_complete = [task_id, &llama] (bool)
  2028. {
  2029. // cancel
  2030. llama.request_cancel(task_id);
  2031. };
  2032. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2033. }
  2034. });
  2035. svr.Post("/infill", [&llama](const httplib::Request &req, httplib::Response &res)
  2036. {
  2037. json data = json::parse(req.body);
  2038. const int task_id = llama.request_completion(data, true);
  2039. if (!json_value(data, "stream", false)) {
  2040. std::string completion_text;
  2041. task_result result = llama.next_result(task_id);
  2042. if (!result.error && result.stop)
  2043. {
  2044. res.set_content(result.result_json.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
  2045. }
  2046. else
  2047. {
  2048. res.status = 404;
  2049. res.set_content(result.result_json["content"], "text/plain");
  2050. return;
  2051. }
  2052. } else {
  2053. const auto chunked_content_provider = [task_id, &llama](size_t, httplib::DataSink & sink) {
  2054. while (true)
  2055. {
  2056. task_result result = llama.next_result(task_id);
  2057. if (!result.error) {
  2058. const std::string str =
  2059. "data: " +
  2060. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace) +
  2061. "\n\n";
  2062. LOG_VERBOSE("data stream", {
  2063. { "to_send", str }
  2064. });
  2065. if (!sink.write(str.c_str(), str.size()))
  2066. {
  2067. return false;
  2068. }
  2069. if (result.stop)
  2070. {
  2071. break;
  2072. }
  2073. }
  2074. else
  2075. {
  2076. break;
  2077. }
  2078. }
  2079. sink.done();
  2080. return true;
  2081. };
  2082. auto on_complete = [task_id, &llama] (bool)
  2083. {
  2084. // cancel
  2085. llama.request_cancel(task_id);
  2086. };
  2087. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2088. }
  2089. });
  2090. svr.Get("/model.json", [&llama](const httplib::Request &, httplib::Response &res)
  2091. {
  2092. const json data = llama.get_model_props();
  2093. return res.set_content(data.dump(), "application/json");
  2094. });
  2095. svr.Options(R"(/.*)", [](const httplib::Request &, httplib::Response &res)
  2096. { return res.set_content("", "application/json"); });
  2097. svr.Post("/tokenize", [&llama](const httplib::Request &req, httplib::Response &res)
  2098. {
  2099. const json body = json::parse(req.body);
  2100. std::vector<llama_token> tokens;
  2101. if (body.count("content") != 0)
  2102. {
  2103. tokens = llama.tokenize(body["content"], false);
  2104. }
  2105. const json data = format_tokenizer_response(tokens);
  2106. return res.set_content(data.dump(), "application/json");
  2107. });
  2108. svr.Post("/detokenize", [&llama](const httplib::Request &req, httplib::Response &res)
  2109. {
  2110. const json body = json::parse(req.body);
  2111. std::string content;
  2112. if (body.count("tokens") != 0)
  2113. {
  2114. const std::vector<llama_token> tokens = body["tokens"];
  2115. content = tokens_to_str(llama.ctx, tokens.cbegin(), tokens.cend());
  2116. }
  2117. const json data = format_detokenized_response(content);
  2118. return res.set_content(data.dump(), "application/json");
  2119. });
  2120. svr.Post("/embedding", [&llama](const httplib::Request &req, httplib::Response &res)
  2121. {
  2122. const json body = json::parse(req.body);
  2123. json prompt;
  2124. if (body.count("content") != 0)
  2125. {
  2126. prompt = body["content"];
  2127. }
  2128. else
  2129. {
  2130. prompt = "";
  2131. }
  2132. const int task_id = llama.request_completion({ {"prompt", prompt}, { "n_predict", 0} }, false);
  2133. task_result result = llama.next_result(task_id);
  2134. return res.set_content(result.result_json.dump(), "application/json");
  2135. });
  2136. svr.set_logger(log_server_request);
  2137. svr.set_exception_handler([](const httplib::Request &, httplib::Response &res, std::exception_ptr ep)
  2138. {
  2139. const char fmt[] = "500 Internal Server Error\n%s";
  2140. char buf[BUFSIZ];
  2141. try
  2142. {
  2143. std::rethrow_exception(std::move(ep));
  2144. }
  2145. catch (std::exception &e)
  2146. {
  2147. snprintf(buf, sizeof(buf), fmt, e.what());
  2148. }
  2149. catch (...)
  2150. {
  2151. snprintf(buf, sizeof(buf), fmt, "Unknown Exception");
  2152. }
  2153. res.set_content(buf, "text/plain");
  2154. res.status = 500;
  2155. });
  2156. svr.set_error_handler([](const httplib::Request &, httplib::Response &res)
  2157. {
  2158. if (res.status == 400)
  2159. {
  2160. res.set_content("Invalid request", "text/plain");
  2161. }
  2162. else if (res.status != 500)
  2163. {
  2164. res.set_content("File Not Found", "text/plain");
  2165. res.status = 404;
  2166. }
  2167. });
  2168. // set timeouts and change hostname and port
  2169. svr.set_read_timeout (sparams.read_timeout);
  2170. svr.set_write_timeout(sparams.write_timeout);
  2171. if (!svr.bind_to_port(sparams.hostname, sparams.port))
  2172. {
  2173. fprintf(stderr, "\ncouldn't bind to server socket: hostname=%s port=%d\n\n", sparams.hostname.c_str(), sparams.port);
  2174. return 1;
  2175. }
  2176. // Set the base directory for serving static files
  2177. svr.set_base_dir(sparams.public_path);
  2178. // to make it ctrl+clickable:
  2179. LOG_TEE("\nllama server listening at http://%s:%d\n\n", sparams.hostname.c_str(), sparams.port);
  2180. LOG_INFO("HTTP server listening", {
  2181. {"hostname", sparams.hostname},
  2182. {"port", sparams.port},
  2183. });
  2184. // run the HTTP server in a thread - see comment below
  2185. std::thread t([&]()
  2186. {
  2187. if (!svr.listen_after_bind())
  2188. {
  2189. return 1;
  2190. }
  2191. return 0;
  2192. });
  2193. // GG: if I put the main loop inside a thread, it crashes on the first request when build in Debug!?
  2194. // "Bus error: 10" - this is on macOS, it does not crash on Linux
  2195. //std::thread t2([&]()
  2196. {
  2197. bool running = true;
  2198. while (running)
  2199. {
  2200. running = llama.update_slots();
  2201. }
  2202. }
  2203. //);
  2204. t.join();
  2205. llama_backend_free();
  2206. return 0;
  2207. }