server.cpp 118 KB

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