server.cpp 88 KB

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