server.cpp 114 KB

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