1
0

server.cpp 90 KB

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