server.cpp 110 KB

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