server.cpp 116 KB

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