server.cpp 91 KB

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