1
0

server.cpp 117 KB

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