server.cpp 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360
  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::vector<std::string> api_keys;
  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 server_state {
  120. SERVER_STATE_LOADING_MODEL, // Server is starting up, model not fully loaded yet
  121. SERVER_STATE_READY, // Server is ready and model is loaded
  122. SERVER_STATE_ERROR // An error occurred, load_model failed
  123. };
  124. enum task_type {
  125. TASK_TYPE_COMPLETION,
  126. TASK_TYPE_CANCEL,
  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. queue_results.push_back(res);
  1169. condition_results.notify_all();
  1170. // done with results, unlock
  1171. lock.unlock();
  1172. // parent multitask, if any, needs to be updated
  1173. if (slot.multitask_id != -1)
  1174. {
  1175. update_multi_task(slot.multitask_id, slot.task_id, res);
  1176. }
  1177. }
  1178. void send_embedding(llama_client_slot &slot)
  1179. {
  1180. std::unique_lock<std::mutex> lock(mutex_results);
  1181. task_result res;
  1182. res.id = slot.task_id;
  1183. res.multitask_id = slot.multitask_id;
  1184. res.error = false;
  1185. res.stop = true;
  1186. const int n_embd = llama_n_embd(model);
  1187. if (!params.embedding)
  1188. {
  1189. LOG_WARNING("embedding disabled", {
  1190. {"params.embedding", params.embedding},
  1191. });
  1192. res.result_json = json
  1193. {
  1194. {"embedding", std::vector<float>(n_embd, 0.0f)},
  1195. };
  1196. }
  1197. else
  1198. {
  1199. const float *data = llama_get_embeddings(ctx);
  1200. std::vector<float> embedding(data, data + n_embd);
  1201. res.result_json = json
  1202. {
  1203. {"embedding", embedding },
  1204. };
  1205. }
  1206. queue_results.push_back(res);
  1207. condition_results.notify_all();
  1208. }
  1209. int request_completion(json data, bool infill, bool embedding, int multitask_id)
  1210. {
  1211. std::unique_lock<std::mutex> lock(mutex_tasks);
  1212. task_server task;
  1213. task.id = id_gen++;
  1214. task.target_id = 0;
  1215. task.data = std::move(data);
  1216. task.infill_mode = infill;
  1217. task.embedding_mode = embedding;
  1218. task.type = TASK_TYPE_COMPLETION;
  1219. task.multitask_id = multitask_id;
  1220. // when a completion task's prompt array is not a singleton, we split it into multiple requests
  1221. if (task.data.count("prompt") && task.data.at("prompt").size() > 1)
  1222. {
  1223. lock.unlock(); // entering new func scope
  1224. return split_multiprompt_task(task);
  1225. }
  1226. // otherwise, it's a single-prompt task, we actually queue it
  1227. queue_tasks.push_back(task);
  1228. condition_tasks.notify_one();
  1229. return task.id;
  1230. }
  1231. task_result next_result(int task_id)
  1232. {
  1233. while (true)
  1234. {
  1235. std::unique_lock<std::mutex> lock(mutex_results);
  1236. condition_results.wait(lock, [&]{
  1237. return !queue_results.empty();
  1238. });
  1239. for (int i = 0; i < (int) queue_results.size(); i++)
  1240. {
  1241. // for now, tasks that have associated parent multitasks just get erased once multitask picks up the result
  1242. if (queue_results[i].multitask_id == task_id)
  1243. {
  1244. update_multi_task(task_id, queue_results[i].id, queue_results[i]);
  1245. queue_results.erase(queue_results.begin() + i);
  1246. continue;
  1247. }
  1248. if (queue_results[i].id == task_id)
  1249. {
  1250. assert(queue_results[i].multitask_id == -1);
  1251. task_result res = queue_results[i];
  1252. queue_results.erase(queue_results.begin() + i);
  1253. return res;
  1254. }
  1255. }
  1256. }
  1257. // never reached
  1258. //return task_result{-1, false, false, {}};
  1259. }
  1260. // for multiple images processing
  1261. bool ingest_images(llama_client_slot &slot, int n_batch)
  1262. {
  1263. int image_idx = 0;
  1264. while (image_idx < (int) slot.images.size())
  1265. {
  1266. slot_image &img = slot.images[image_idx];
  1267. // process prefix prompt
  1268. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch)
  1269. {
  1270. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  1271. llama_batch batch_view = {
  1272. n_tokens,
  1273. batch.token + i,
  1274. nullptr,
  1275. batch.pos + i,
  1276. batch.n_seq_id + i,
  1277. batch.seq_id + i,
  1278. batch.logits + i,
  1279. 0, 0, 0, // unused
  1280. };
  1281. if (llama_decode(ctx, batch_view))
  1282. {
  1283. LOG_TEE("%s : failed to eval\n", __func__);
  1284. return false;
  1285. }
  1286. }
  1287. // process image with llm
  1288. for (int i = 0; i < img.image_tokens; i += n_batch)
  1289. {
  1290. int n_eval = img.image_tokens - i;
  1291. if (n_eval > n_batch)
  1292. {
  1293. n_eval = n_batch;
  1294. }
  1295. const int n_embd = llama_n_embd(model);
  1296. llama_batch batch_img = { n_eval, nullptr, (img.image_embedding + i * n_embd), nullptr, nullptr, nullptr, nullptr, slot.n_past, 1, 0, };
  1297. if (llama_decode(ctx, batch_img))
  1298. {
  1299. LOG_TEE("%s : failed to eval image\n", __func__);
  1300. return false;
  1301. }
  1302. slot.n_past += n_eval;
  1303. }
  1304. image_idx++;
  1305. llama_batch_clear(batch);
  1306. // append prefix of next image
  1307. const auto json_prompt = (image_idx >= (int) slot.images.size()) ?
  1308. slot.params.input_suffix : // no more images, then process suffix prompt
  1309. (json)(slot.images[image_idx].prefix_prompt);
  1310. std::vector<llama_token> append_tokens = tokenize(json_prompt, false); // has next image
  1311. for (int i = 0; i < (int) append_tokens.size(); ++i)
  1312. {
  1313. llama_batch_add(batch, append_tokens[i], slot.n_past, { slot.id }, true);
  1314. slot.n_past += 1;
  1315. }
  1316. }
  1317. return true;
  1318. }
  1319. void request_cancel(int task_id)
  1320. {
  1321. std::unique_lock<std::mutex> lock(mutex_tasks);
  1322. task_server task;
  1323. task.id = id_gen++;
  1324. task.type = TASK_TYPE_CANCEL;
  1325. task.target_id = task_id;
  1326. queue_tasks.push_back(task);
  1327. condition_tasks.notify_one();
  1328. }
  1329. int split_multiprompt_task(task_server& multiprompt_task)
  1330. {
  1331. int prompt_count = multiprompt_task.data.at("prompt").size();
  1332. assert(prompt_count > 1);
  1333. int multitask_id = id_gen++;
  1334. std::vector<int> subtask_ids(prompt_count);
  1335. for (int i = 0; i < prompt_count; i++)
  1336. {
  1337. json subtask_data = multiprompt_task.data;
  1338. subtask_data["prompt"] = subtask_data["prompt"][i];
  1339. // subtasks inherit everything else (infill mode, embedding mode, etc.)
  1340. subtask_ids[i] = request_completion(subtask_data, multiprompt_task.infill_mode, multiprompt_task.embedding_mode, multitask_id);
  1341. }
  1342. // queue up the multitask so we can track its subtask progression
  1343. add_multi_task(multitask_id, subtask_ids);
  1344. return multitask_id;
  1345. }
  1346. void process_tasks()
  1347. {
  1348. std::unique_lock<std::mutex> lock(mutex_tasks);
  1349. while (!queue_tasks.empty())
  1350. {
  1351. task_server task = queue_tasks.front();
  1352. queue_tasks.erase(queue_tasks.begin());
  1353. switch (task.type)
  1354. {
  1355. case TASK_TYPE_COMPLETION: {
  1356. llama_client_slot *slot = get_slot(json_value(task.data, "slot_id", -1));
  1357. if (slot == nullptr)
  1358. {
  1359. LOG_TEE("slot unavailable\n");
  1360. // send error result
  1361. send_error(task, "slot unavailable");
  1362. return;
  1363. }
  1364. if (task.data.contains("system_prompt"))
  1365. {
  1366. process_system_prompt_data(task.data["system_prompt"]);
  1367. }
  1368. slot->reset();
  1369. slot->infill = task.infill_mode;
  1370. slot->embedding = task.embedding_mode;
  1371. slot->task_id = task.id;
  1372. slot->multitask_id = task.multitask_id;
  1373. if (!launch_slot_with_data(slot, task.data))
  1374. {
  1375. // send error result
  1376. send_error(task, "internal_error");
  1377. break;
  1378. }
  1379. } break;
  1380. case TASK_TYPE_CANCEL: { // release slot linked with the task id
  1381. for (auto & slot : slots)
  1382. {
  1383. if (slot.task_id == task.target_id)
  1384. {
  1385. slot.release();
  1386. break;
  1387. }
  1388. }
  1389. } break;
  1390. }
  1391. }
  1392. // remove finished multitasks from the queue of multitasks, and add the corresponding result to the result queue
  1393. std::vector<task_result> agg_results;
  1394. auto queue_iterator = queue_multitasks.begin();
  1395. while (queue_iterator != queue_multitasks.end())
  1396. {
  1397. if (queue_iterator->subtasks_remaining.empty())
  1398. {
  1399. // all subtasks done == multitask is done
  1400. task_result aggregate_result;
  1401. aggregate_result.id = queue_iterator->id;
  1402. aggregate_result.stop = true;
  1403. aggregate_result.error = false;
  1404. // collect json results into one json result
  1405. std::vector<json> result_jsons;
  1406. for (auto& subres : queue_iterator->results)
  1407. {
  1408. result_jsons.push_back(subres.result_json);
  1409. aggregate_result.error = aggregate_result.error && subres.error;
  1410. }
  1411. aggregate_result.result_json = json{ "results", result_jsons };
  1412. agg_results.push_back(aggregate_result);
  1413. condition_results.notify_all();
  1414. queue_iterator = queue_multitasks.erase(queue_iterator);
  1415. }
  1416. else
  1417. {
  1418. ++queue_iterator;
  1419. }
  1420. }
  1421. // done with tasks, unlock
  1422. lock.unlock();
  1423. // copy aggregate results of complete multi-tasks to the results queue
  1424. std::lock_guard<std::mutex> lock_results(mutex_results);
  1425. queue_results.insert(queue_results.end(), agg_results.begin(), agg_results.end());
  1426. }
  1427. bool update_slots() {
  1428. // attend tasks
  1429. process_tasks();
  1430. // update the system prompt wait until all slots are idle state
  1431. if (system_need_update && all_slots_are_idle)
  1432. {
  1433. LOG_TEE("updating system prompt\n");
  1434. update_system_prompt();
  1435. }
  1436. llama_batch_clear(batch);
  1437. if (all_slots_are_idle)
  1438. {
  1439. if (system_prompt.empty() && clean_kv_cache)
  1440. {
  1441. LOG_TEE("all slots are idle and system prompt is empty, clear the KV cache\n");
  1442. kv_cache_clear();
  1443. }
  1444. std::unique_lock<std::mutex> lock(mutex_tasks);
  1445. condition_tasks.wait(lock, [&]{
  1446. return !queue_tasks.empty();
  1447. });
  1448. }
  1449. for (llama_client_slot &slot : slots)
  1450. {
  1451. if (slot.is_processing() && slot.cache_tokens.size() >= (size_t) slot.n_ctx)
  1452. {
  1453. // Shift context
  1454. const int n_left = slot.n_past - slot.params.n_keep - 1;
  1455. const int n_discard = n_left / 2;
  1456. 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);
  1457. llama_kv_cache_seq_rm (ctx, slot.id, slot.params.n_keep + 1 , slot.params.n_keep + n_discard + 1);
  1458. llama_kv_cache_seq_shift(ctx, slot.id, slot.params.n_keep + 1 + n_discard, slot.n_past, -n_discard);
  1459. for (size_t i = slot.params.n_keep + 1 + n_discard; i < slot.cache_tokens.size(); i++)
  1460. {
  1461. slot.cache_tokens[i - n_discard] = slot.cache_tokens[i];
  1462. }
  1463. slot.cache_tokens.resize(slot.cache_tokens.size() - n_discard);
  1464. slot.n_past -= n_discard;
  1465. slot.truncated = true;
  1466. LOG_VERBOSE("context shift", {
  1467. {"n_ctx", n_ctx},
  1468. {"n_keep", params.n_keep},
  1469. {"n_left", n_left},
  1470. });
  1471. }
  1472. }
  1473. // decode any currently ongoing sequences
  1474. for (auto & slot : slots)
  1475. {
  1476. // release the slot
  1477. if (slot.command == RELEASE)
  1478. {
  1479. slot.state = IDLE;
  1480. slot.command = NONE;
  1481. slot.t_last_used = ggml_time_us();
  1482. LOG_TEE("slot %d released (%d tokens in cache)\n", slot.id, (int) slot.cache_tokens.size());
  1483. continue;
  1484. }
  1485. if (slot.state == IDLE)
  1486. {
  1487. continue;
  1488. }
  1489. slot.i_batch = batch.n_tokens;
  1490. llama_batch_add(batch, slot.sampled, system_tokens.size() + slot.n_past, { slot.id }, true);
  1491. slot.n_past += 1;
  1492. }
  1493. // process in chunks of params.n_batch
  1494. int32_t n_batch = params.n_batch;
  1495. // assign workload to the slots
  1496. if (params.cont_batching || batch.n_tokens == 0)
  1497. {
  1498. for (auto & slot : slots)
  1499. {
  1500. const bool has_prompt = slot.prompt.is_array() || (slot.prompt.is_string() && !slot.prompt.get<std::string>().empty()) || !slot.images.empty();
  1501. // empty prompt passed -> release the slot and send empty response
  1502. // note: infill mode allows empty prompt
  1503. if (slot.state == IDLE && slot.command == LOAD_PROMPT && !has_prompt && !slot.infill)
  1504. {
  1505. slot.release();
  1506. slot.print_timings();
  1507. send_final_response(slot);
  1508. continue;
  1509. }
  1510. // need process the prompt
  1511. if (slot.state == IDLE && slot.command == LOAD_PROMPT)
  1512. {
  1513. slot.state = PROCESSING;
  1514. slot.command = NONE;
  1515. std::vector<llama_token> prompt_tokens;
  1516. slot.t_start_process_prompt = ggml_time_us();
  1517. slot.t_start_genereration = 0;
  1518. if (slot.infill)
  1519. {
  1520. bool suff_rm_leading_spc = true;
  1521. if (params.input_suffix.find_first_of(' ') == 0 && params.input_suffix.size() > 1)
  1522. {
  1523. params.input_suffix.erase(0, 1);
  1524. suff_rm_leading_spc = false;
  1525. }
  1526. auto prefix_tokens = tokenize(slot.params.input_prefix, false);
  1527. auto suffix_tokens = tokenize(slot.params.input_suffix, false);
  1528. const int space_token = 29871; // TODO: this should not be hardcoded
  1529. if (suff_rm_leading_spc && !suffix_tokens.empty() && suffix_tokens[0] == space_token) {
  1530. suffix_tokens.erase(suffix_tokens.begin());
  1531. }
  1532. prefix_tokens.insert(prefix_tokens.begin(), llama_token_prefix(model));
  1533. prefix_tokens.insert(prefix_tokens.begin(), llama_token_bos(model)); // always add BOS
  1534. prefix_tokens.insert(prefix_tokens.end(), llama_token_suffix(model));
  1535. prefix_tokens.insert(prefix_tokens.end(), suffix_tokens.begin(), suffix_tokens.end());
  1536. prefix_tokens.push_back(llama_token_middle(model));
  1537. prompt_tokens = prefix_tokens;
  1538. }
  1539. else
  1540. {
  1541. prompt_tokens = tokenize(slot.prompt, system_prompt.empty() && add_bos_token); // add BOS if there isn't system prompt
  1542. }
  1543. slot.num_prompt_tokens = prompt_tokens.size();
  1544. if (slot.params.n_keep < 0)
  1545. {
  1546. slot.params.n_keep = slot.num_prompt_tokens;
  1547. }
  1548. slot.params.n_keep = std::min(slot.n_ctx - 4, slot.params.n_keep);
  1549. // if input prompt is too big, truncate it
  1550. if (slot.num_prompt_tokens >= slot.n_ctx)
  1551. {
  1552. const int n_left = slot.n_ctx - slot.params.n_keep;
  1553. const int n_block_size = n_left / 2;
  1554. const int erased_blocks = (slot.num_prompt_tokens - slot.params.n_keep - n_block_size) / n_block_size;
  1555. std::vector<llama_token> new_tokens(prompt_tokens.begin(), prompt_tokens.begin() + slot.params.n_keep);
  1556. new_tokens.insert(new_tokens.end(), prompt_tokens.begin() + slot.params.n_keep + erased_blocks * n_block_size, prompt_tokens.end());
  1557. LOG_VERBOSE("input truncated", {
  1558. {"n_ctx", slot.n_ctx},
  1559. {"n_keep", slot.params.n_keep},
  1560. {"n_left", n_left},
  1561. {"new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend())},
  1562. });
  1563. slot.truncated = true;
  1564. prompt_tokens = new_tokens;
  1565. slot.num_prompt_tokens = prompt_tokens.size();
  1566. GGML_ASSERT(slot.num_prompt_tokens < slot.n_ctx);
  1567. }
  1568. if (!slot.params.cache_prompt)
  1569. {
  1570. llama_sampling_reset(slot.ctx_sampling);
  1571. slot.n_past = 0;
  1572. slot.num_prompt_tokens_processed = slot.num_prompt_tokens;
  1573. }
  1574. else
  1575. {
  1576. // push the prompt into the sampling context (do not apply grammar)
  1577. for (auto &token : prompt_tokens)
  1578. {
  1579. llama_sampling_accept(slot.ctx_sampling, ctx, token, false);
  1580. }
  1581. slot.n_past = common_part(slot.cache_tokens, prompt_tokens);
  1582. slot.num_prompt_tokens_processed = slot.num_prompt_tokens - slot.n_past;
  1583. LOG_TEE("slot %d : in cache: %i tokens | to process: %i tokens\n", slot.id, slot.n_past, slot.num_prompt_tokens_processed);
  1584. }
  1585. LOG_TEE("slot %d : kv cache rm - [%d, end)\n", slot.id, (int) system_tokens.size() + slot.n_past);
  1586. llama_kv_cache_seq_rm(ctx, slot.id, system_tokens.size() + slot.n_past, -1);
  1587. slot.cache_tokens = prompt_tokens;
  1588. if (slot.n_past == slot.num_prompt_tokens && slot.n_past > 0)
  1589. {
  1590. // we have to evaluate at least 1 token to generate logits.
  1591. LOG_TEE("slot %d : we have to evaluate at least 1 token to generate logits\n", slot.id);
  1592. slot.n_past--;
  1593. }
  1594. LOG_VERBOSE("prompt ingested", {
  1595. {"n_past", slot.n_past},
  1596. {"cached", tokens_to_str(ctx, slot.cache_tokens.cbegin(), slot.cache_tokens.cbegin() + slot.n_past)},
  1597. {"to_eval", tokens_to_str(ctx, slot.cache_tokens.cbegin() + slot.n_past, slot.cache_tokens.cend())},
  1598. });
  1599. const bool has_images = process_images(slot);
  1600. // process the prefix of first image
  1601. std::vector<llama_token> prefix_tokens = has_images ? tokenize(slot.images[0].prefix_prompt, add_bos_token) : prompt_tokens;
  1602. for (; slot.n_past < (int) prefix_tokens.size(); ++slot.n_past)
  1603. {
  1604. llama_batch_add(batch, prefix_tokens[slot.n_past], system_tokens.size() + slot.n_past, { slot.id }, false);
  1605. }
  1606. if (has_images && !ingest_images(slot, n_batch))
  1607. {
  1608. LOG_TEE("failed processing images\n");
  1609. return false;
  1610. }
  1611. // extract the logits only for the last token
  1612. if (batch.n_tokens > 0)
  1613. {
  1614. batch.logits[batch.n_tokens - 1] = true;
  1615. }
  1616. slot.n_decoded = 0;
  1617. slot.i_batch = batch.n_tokens - 1;
  1618. }
  1619. }
  1620. }
  1621. if (batch.n_tokens == 0)
  1622. {
  1623. all_slots_are_idle = true;
  1624. return true;
  1625. }
  1626. for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch)
  1627. {
  1628. const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
  1629. llama_batch batch_view =
  1630. {
  1631. n_tokens,
  1632. batch.token + i,
  1633. nullptr,
  1634. batch.pos + i,
  1635. batch.n_seq_id + i,
  1636. batch.seq_id + i,
  1637. batch.logits + i,
  1638. 0, 0, 0, // unused
  1639. };
  1640. const int ret = llama_decode(ctx, batch_view);
  1641. if (ret != 0)
  1642. {
  1643. if (n_batch == 1 || ret < 0)
  1644. {
  1645. // if you get here, it means the KV cache is full - try increasing it via the context size
  1646. LOG_TEE("%s : failed to decode the batch, n_batch = %d, ret = %d\n", __func__, n_batch, ret);
  1647. return false;
  1648. }
  1649. LOG_TEE("%s : failed to find free space in the KV cache, retrying with smaller n_batch = %d\n", __func__, n_batch / 2);
  1650. // retry with half the batch size to try to find a free slot in the KV cache
  1651. n_batch /= 2;
  1652. i -= n_batch;
  1653. continue;
  1654. }
  1655. for (auto & slot : slots)
  1656. {
  1657. if (slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens))
  1658. {
  1659. continue;
  1660. }
  1661. // prompt evaluated for embedding
  1662. if (slot.embedding)
  1663. {
  1664. send_embedding(slot);
  1665. slot.release();
  1666. slot.i_batch = -1;
  1667. return true;
  1668. }
  1669. completion_token_output result;
  1670. const llama_token id = llama_sampling_sample(slot.ctx_sampling, ctx, NULL, slot.i_batch - i);
  1671. llama_sampling_accept(slot.ctx_sampling, ctx, id, true);
  1672. slot.n_decoded += 1;
  1673. if (slot.n_decoded == 1)
  1674. {
  1675. slot.t_start_genereration = ggml_time_us();
  1676. slot.t_prompt_processing = (slot.t_start_genereration - slot.t_start_process_prompt) / 1e3;
  1677. }
  1678. llama_token_data_array cur_p = { slot.ctx_sampling->cur.data(), slot.ctx_sampling->cur.size(), false };
  1679. result.tok = id;
  1680. const int32_t n_probs = slot.sparams.n_probs;
  1681. if (slot.sparams.temp <= 0 && n_probs > 0)
  1682. {
  1683. // for llama_sample_token_greedy we need to sort candidates
  1684. llama_sample_softmax(ctx, &cur_p);
  1685. }
  1686. for (size_t i = 0; i < std::min(cur_p.size, (size_t)n_probs); ++i)
  1687. {
  1688. result.probs.push_back({cur_p.data[i].id, cur_p.data[i].p});
  1689. }
  1690. if (!process_token(result, slot))
  1691. {
  1692. slot.release();
  1693. slot.print_timings();
  1694. send_final_response(slot);
  1695. }
  1696. slot.i_batch = -1;
  1697. }
  1698. }
  1699. return true;
  1700. }
  1701. };
  1702. static void server_print_usage(const char *argv0, const gpt_params &params,
  1703. const server_params &sparams)
  1704. {
  1705. printf("usage: %s [options]\n", argv0);
  1706. printf("\n");
  1707. printf("options:\n");
  1708. printf(" -h, --help show this help message and exit\n");
  1709. printf(" -v, --verbose verbose output (default: %s)\n", server_verbose ? "enabled" : "disabled");
  1710. printf(" -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  1711. printf(" -tb N, --threads-batch N number of threads to use during batch and prompt processing (default: same as --threads)\n");
  1712. printf(" -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  1713. printf(" --rope-scaling {none,linear,yarn}\n");
  1714. printf(" RoPE frequency scaling method, defaults to linear unless specified by the model\n");
  1715. printf(" --rope-freq-base N RoPE base frequency (default: loaded from model)\n");
  1716. printf(" --rope-freq-scale N RoPE frequency scaling factor, expands context by a factor of 1/N\n");
  1717. printf(" --yarn-ext-factor N YaRN: extrapolation mix factor (default: 1.0, 0.0 = full interpolation)\n");
  1718. printf(" --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)\n");
  1719. printf(" --yarn-beta-slow N YaRN: high correction dim or alpha (default: %.1f)\n", params.yarn_beta_slow);
  1720. printf(" --yarn-beta-fast N YaRN: low correction dim or beta (default: %.1f)\n", params.yarn_beta_fast);
  1721. printf(" -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  1722. printf(" --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  1723. printf(" not recommended: doubles context memory required and no measurable increase in quality\n");
  1724. if (llama_mlock_supported())
  1725. {
  1726. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  1727. }
  1728. if (llama_mmap_supported())
  1729. {
  1730. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  1731. }
  1732. printf(" --numa attempt optimizations that help on some NUMA systems\n");
  1733. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  1734. printf(" -ngl N, --n-gpu-layers N\n");
  1735. printf(" number of layers to store in VRAM\n");
  1736. printf(" -sm SPLIT_MODE, --split-mode SPLIT_MODE\n");
  1737. printf(" how to split the model across multiple GPUs, one of:\n");
  1738. printf(" - none: use one GPU only\n");
  1739. printf(" - layer (default): split layers and KV across GPUs\n");
  1740. printf(" - row: split rows across GPUs\n");
  1741. printf(" -ts SPLIT --tensor-split SPLIT\n");
  1742. printf(" fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1\n");
  1743. printf(" -mg i, --main-gpu i the GPU to use for the model (with split-mode = none),\n");
  1744. printf(" or for intermediate results and KV (with split-mode = row)\n");
  1745. #endif
  1746. printf(" -m FNAME, --model FNAME\n");
  1747. printf(" model path (default: %s)\n", params.model.c_str());
  1748. printf(" -a ALIAS, --alias ALIAS\n");
  1749. printf(" set an alias for the model, will be added as `model` field in completion response\n");
  1750. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  1751. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  1752. printf(" --host ip address to listen (default (default: %s)\n", sparams.hostname.c_str());
  1753. printf(" --port PORT port to listen (default (default: %d)\n", sparams.port);
  1754. printf(" --path PUBLIC_PATH path from which to serve static files (default %s)\n", sparams.public_path.c_str());
  1755. printf(" --api-key API_KEY optional api key to enhance server security. If set, requests must include this key for access.\n");
  1756. printf(" --api-key-file FNAME path to file containing api keys delimited by new lines. If set, requests must include one of the keys for access.\n");
  1757. printf(" -to N, --timeout N server read/write timeout in seconds (default: %d)\n", sparams.read_timeout);
  1758. printf(" --embedding enable embedding vector output (default: %s)\n", params.embedding ? "enabled" : "disabled");
  1759. printf(" -np N, --parallel N number of slots for process requests (default: %d)\n", params.n_parallel);
  1760. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)\n");
  1761. printf(" -spf FNAME, --system-prompt-file FNAME\n");
  1762. printf(" Set a file to load a system prompt (initial prompt of all slots), this is useful for chat applications.\n");
  1763. printf(" --mmproj MMPROJ_FILE path to a multimodal projector file for LLaVA.\n");
  1764. printf(" --log-disable disables logging to a file.\n");
  1765. printf("\n");
  1766. printf(" --override-kv KEY=TYPE:VALUE\n");
  1767. printf(" advanced option to override model metadata by key. may be specified multiple times.\n");
  1768. printf(" types: int, float, bool. example: --override-kv tokenizer.ggml.add_bos_token=bool:false\n");
  1769. printf("\n");
  1770. }
  1771. static void server_params_parse(int argc, char **argv, server_params &sparams,
  1772. gpt_params &params, llama_server_context& llama)
  1773. {
  1774. gpt_params default_params;
  1775. server_params default_sparams;
  1776. std::string arg;
  1777. bool invalid_param = false;
  1778. for (int i = 1; i < argc; i++)
  1779. {
  1780. arg = argv[i];
  1781. if (arg == "--port")
  1782. {
  1783. if (++i >= argc)
  1784. {
  1785. invalid_param = true;
  1786. break;
  1787. }
  1788. sparams.port = std::stoi(argv[i]);
  1789. }
  1790. else if (arg == "--host")
  1791. {
  1792. if (++i >= argc)
  1793. {
  1794. invalid_param = true;
  1795. break;
  1796. }
  1797. sparams.hostname = argv[i];
  1798. }
  1799. else if (arg == "--path")
  1800. {
  1801. if (++i >= argc)
  1802. {
  1803. invalid_param = true;
  1804. break;
  1805. }
  1806. sparams.public_path = argv[i];
  1807. }
  1808. else if (arg == "--api-key")
  1809. {
  1810. if (++i >= argc)
  1811. {
  1812. invalid_param = true;
  1813. break;
  1814. }
  1815. sparams.api_keys.push_back(argv[i]);
  1816. }
  1817. else if (arg == "--api-key-file")
  1818. {
  1819. if (++i >= argc)
  1820. {
  1821. invalid_param = true;
  1822. break;
  1823. }
  1824. std::ifstream key_file(argv[i]);
  1825. if (!key_file) {
  1826. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1827. invalid_param = true;
  1828. break;
  1829. }
  1830. std::string key;
  1831. while (std::getline(key_file, key)) {
  1832. if (key.size() > 0) {
  1833. sparams.api_keys.push_back(key);
  1834. }
  1835. }
  1836. key_file.close();
  1837. }
  1838. else if (arg == "--timeout" || arg == "-to")
  1839. {
  1840. if (++i >= argc)
  1841. {
  1842. invalid_param = true;
  1843. break;
  1844. }
  1845. sparams.read_timeout = std::stoi(argv[i]);
  1846. sparams.write_timeout = std::stoi(argv[i]);
  1847. }
  1848. else if (arg == "-m" || arg == "--model")
  1849. {
  1850. if (++i >= argc)
  1851. {
  1852. invalid_param = true;
  1853. break;
  1854. }
  1855. params.model = argv[i];
  1856. }
  1857. else if (arg == "-a" || arg == "--alias")
  1858. {
  1859. if (++i >= argc)
  1860. {
  1861. invalid_param = true;
  1862. break;
  1863. }
  1864. params.model_alias = argv[i];
  1865. }
  1866. else if (arg == "-h" || arg == "--help")
  1867. {
  1868. server_print_usage(argv[0], default_params, default_sparams);
  1869. exit(0);
  1870. }
  1871. else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size")
  1872. {
  1873. if (++i >= argc)
  1874. {
  1875. invalid_param = true;
  1876. break;
  1877. }
  1878. params.n_ctx = std::stoi(argv[i]);
  1879. }
  1880. else if (arg == "--rope-scaling")
  1881. {
  1882. if (++i >= argc)
  1883. {
  1884. invalid_param = true;
  1885. break;
  1886. }
  1887. std::string value(argv[i]);
  1888. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_NONE; }
  1889. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_LINEAR; }
  1890. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_YARN; }
  1891. else { invalid_param = true; break; }
  1892. }
  1893. else if (arg == "--rope-freq-base")
  1894. {
  1895. if (++i >= argc)
  1896. {
  1897. invalid_param = true;
  1898. break;
  1899. }
  1900. params.rope_freq_base = std::stof(argv[i]);
  1901. }
  1902. else if (arg == "--rope-freq-scale")
  1903. {
  1904. if (++i >= argc)
  1905. {
  1906. invalid_param = true;
  1907. break;
  1908. }
  1909. params.rope_freq_scale = std::stof(argv[i]);
  1910. }
  1911. else if (arg == "--yarn-ext-factor")
  1912. {
  1913. if (++i >= argc) {
  1914. invalid_param = true;
  1915. break;
  1916. }
  1917. params.yarn_ext_factor = std::stof(argv[i]);
  1918. }
  1919. else if (arg == "--yarn-attn-factor")
  1920. {
  1921. if (++i >= argc) {
  1922. invalid_param = true;
  1923. break;
  1924. }
  1925. params.yarn_attn_factor = std::stof(argv[i]);
  1926. }
  1927. else if (arg == "--yarn-beta-fast")
  1928. {
  1929. if (++i >= argc) {
  1930. invalid_param = true;
  1931. break;
  1932. }
  1933. params.yarn_beta_fast = std::stof(argv[i]);
  1934. }
  1935. else if (arg == "--yarn-beta-slow")
  1936. {
  1937. if (++i >= argc) {
  1938. invalid_param = true;
  1939. break;
  1940. }
  1941. params.yarn_beta_slow = std::stof(argv[i]);
  1942. }
  1943. else if (arg == "--threads" || arg == "-t")
  1944. {
  1945. if (++i >= argc)
  1946. {
  1947. invalid_param = true;
  1948. break;
  1949. }
  1950. params.n_threads = std::stoi(argv[i]);
  1951. }
  1952. else if (arg == "--threads-batch" || arg == "-tb")
  1953. {
  1954. if (++i >= argc)
  1955. {
  1956. invalid_param = true;
  1957. break;
  1958. }
  1959. params.n_threads_batch = std::stoi(argv[i]);
  1960. }
  1961. else if (arg == "-b" || arg == "--batch-size")
  1962. {
  1963. if (++i >= argc)
  1964. {
  1965. invalid_param = true;
  1966. break;
  1967. }
  1968. params.n_batch = std::stoi(argv[i]);
  1969. params.n_batch = std::min(512, params.n_batch);
  1970. }
  1971. else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers")
  1972. {
  1973. if (++i >= argc)
  1974. {
  1975. invalid_param = true;
  1976. break;
  1977. }
  1978. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  1979. params.n_gpu_layers = std::stoi(argv[i]);
  1980. #else
  1981. LOG_WARNING("Not compiled with GPU offload support, --n-gpu-layers option will be ignored. "
  1982. "See main README.md for information on enabling GPU BLAS support",
  1983. {{"n_gpu_layers", params.n_gpu_layers}});
  1984. #endif
  1985. }
  1986. else if (arg == "--split-mode" || arg == "-sm")
  1987. {
  1988. if (++i >= argc) {
  1989. invalid_param = true;
  1990. break;
  1991. }
  1992. std::string arg_next = argv[i];
  1993. if (arg_next == "none")
  1994. {
  1995. params.split_mode = LLAMA_SPLIT_NONE;
  1996. }
  1997. else if (arg_next == "layer")
  1998. {
  1999. params.split_mode = LLAMA_SPLIT_LAYER;
  2000. }
  2001. else if (arg_next == "row")
  2002. {
  2003. params.split_mode = LLAMA_SPLIT_ROW;
  2004. }
  2005. else {
  2006. invalid_param = true;
  2007. break;
  2008. }
  2009. #ifndef GGML_USE_CUBLAS
  2010. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. Setting the split mode has no effect.\n");
  2011. #endif // GGML_USE_CUBLAS
  2012. }
  2013. else if (arg == "--tensor-split" || arg == "-ts")
  2014. {
  2015. if (++i >= argc)
  2016. {
  2017. invalid_param = true;
  2018. break;
  2019. }
  2020. #ifdef GGML_USE_CUBLAS
  2021. std::string arg_next = argv[i];
  2022. // split string by , and /
  2023. const std::regex regex{R"([,/]+)"};
  2024. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  2025. std::vector<std::string> split_arg{it, {}};
  2026. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  2027. for (size_t i_device = 0; i_device < LLAMA_MAX_DEVICES; ++i_device)
  2028. {
  2029. if (i_device < split_arg.size())
  2030. {
  2031. params.tensor_split[i_device] = std::stof(split_arg[i_device]);
  2032. }
  2033. else
  2034. {
  2035. params.tensor_split[i_device] = 0.0f;
  2036. }
  2037. }
  2038. #else
  2039. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n", {});
  2040. #endif // GGML_USE_CUBLAS
  2041. }
  2042. else if (arg == "--no-mul-mat-q" || arg == "-nommq")
  2043. {
  2044. #ifdef GGML_USE_CUBLAS
  2045. params.mul_mat_q = false;
  2046. #else
  2047. LOG_WARNING("warning: llama.cpp was compiled without cuBLAS. Disabling mul_mat_q kernels has no effect.\n", {});
  2048. #endif // GGML_USE_CUBLAS
  2049. }
  2050. else if (arg == "--main-gpu" || arg == "-mg")
  2051. {
  2052. if (++i >= argc)
  2053. {
  2054. invalid_param = true;
  2055. break;
  2056. }
  2057. #ifdef GGML_USE_CUBLAS
  2058. params.main_gpu = std::stoi(argv[i]);
  2059. #else
  2060. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.", {});
  2061. #endif
  2062. }
  2063. else if (arg == "--lora")
  2064. {
  2065. if (++i >= argc)
  2066. {
  2067. invalid_param = true;
  2068. break;
  2069. }
  2070. params.lora_adapter.push_back(std::make_tuple(argv[i], 1.0f));
  2071. params.use_mmap = false;
  2072. }
  2073. else if (arg == "--lora-scaled")
  2074. {
  2075. if (++i >= argc)
  2076. {
  2077. invalid_param = true;
  2078. break;
  2079. }
  2080. const char * lora_adapter = argv[i];
  2081. if (++i >= argc)
  2082. {
  2083. invalid_param = true;
  2084. break;
  2085. }
  2086. params.lora_adapter.push_back(std::make_tuple(lora_adapter, std::stof(argv[i])));
  2087. params.use_mmap = false;
  2088. }
  2089. else if (arg == "--lora-base")
  2090. {
  2091. if (++i >= argc)
  2092. {
  2093. invalid_param = true;
  2094. break;
  2095. }
  2096. params.lora_base = argv[i];
  2097. }
  2098. else if (arg == "-v" || arg == "--verbose")
  2099. {
  2100. #if SERVER_VERBOSE != 1
  2101. LOG_WARNING("server.cpp is not built with verbose logging.", {});
  2102. #else
  2103. server_verbose = true;
  2104. #endif
  2105. }
  2106. else if (arg == "--mlock")
  2107. {
  2108. params.use_mlock = true;
  2109. }
  2110. else if (arg == "--no-mmap")
  2111. {
  2112. params.use_mmap = false;
  2113. }
  2114. else if (arg == "--numa")
  2115. {
  2116. params.numa = true;
  2117. }
  2118. else if (arg == "--embedding")
  2119. {
  2120. params.embedding = true;
  2121. }
  2122. else if (arg == "-cb" || arg == "--cont-batching")
  2123. {
  2124. params.cont_batching = true;
  2125. }
  2126. else if (arg == "-np" || arg == "--parallel")
  2127. {
  2128. if (++i >= argc)
  2129. {
  2130. invalid_param = true;
  2131. break;
  2132. }
  2133. params.n_parallel = std::stoi(argv[i]);
  2134. } else if (arg == "-n" || arg == "--n-predict")
  2135. {
  2136. if (++i >= argc)
  2137. {
  2138. invalid_param = true;
  2139. break;
  2140. }
  2141. params.n_predict = std::stoi(argv[i]);
  2142. } else if (arg == "-spf" || arg == "--system-prompt-file")
  2143. {
  2144. if (++i >= argc)
  2145. {
  2146. invalid_param = true;
  2147. break;
  2148. }
  2149. std::ifstream file(argv[i]);
  2150. if (!file) {
  2151. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  2152. invalid_param = true;
  2153. break;
  2154. }
  2155. std::string systm_content;
  2156. std::copy(
  2157. std::istreambuf_iterator<char>(file),
  2158. std::istreambuf_iterator<char>(),
  2159. std::back_inserter(systm_content)
  2160. );
  2161. llama.process_system_prompt_data(json::parse(systm_content));
  2162. }
  2163. else if(arg == "--mmproj")
  2164. {
  2165. if (++i >= argc)
  2166. {
  2167. invalid_param = true;
  2168. break;
  2169. }
  2170. params.mmproj = argv[i];
  2171. }
  2172. else if (arg == "--log-disable")
  2173. {
  2174. log_set_target(stdout);
  2175. LOG_INFO("logging to file is disabled.", {});
  2176. }
  2177. else if (arg == "--override-kv")
  2178. {
  2179. if (++i >= argc) {
  2180. invalid_param = true;
  2181. break;
  2182. }
  2183. char * sep = strchr(argv[i], '=');
  2184. if (sep == nullptr || sep - argv[i] >= 128) {
  2185. fprintf(stderr, "error: Malformed KV override: %s\n", argv[i]);
  2186. invalid_param = true;
  2187. break;
  2188. }
  2189. struct llama_model_kv_override kvo;
  2190. std::strncpy(kvo.key, argv[i], sep - argv[i]);
  2191. kvo.key[sep - argv[i]] = 0;
  2192. sep++;
  2193. if (strncmp(sep, "int:", 4) == 0) {
  2194. sep += 4;
  2195. kvo.tag = LLAMA_KV_OVERRIDE_INT;
  2196. kvo.int_value = std::atol(sep);
  2197. } else if (strncmp(sep, "float:", 6) == 0) {
  2198. sep += 6;
  2199. kvo.tag = LLAMA_KV_OVERRIDE_FLOAT;
  2200. kvo.float_value = std::atof(sep);
  2201. } else if (strncmp(sep, "bool:", 5) == 0) {
  2202. sep += 5;
  2203. kvo.tag = LLAMA_KV_OVERRIDE_BOOL;
  2204. if (std::strcmp(sep, "true") == 0) {
  2205. kvo.bool_value = true;
  2206. } else if (std::strcmp(sep, "false") == 0) {
  2207. kvo.bool_value = false;
  2208. } else {
  2209. fprintf(stderr, "error: Invalid boolean value for KV override: %s\n", argv[i]);
  2210. invalid_param = true;
  2211. break;
  2212. }
  2213. } else {
  2214. fprintf(stderr, "error: Invalid type for KV override: %s\n", argv[i]);
  2215. invalid_param = true;
  2216. break;
  2217. }
  2218. params.kv_overrides.push_back(kvo);
  2219. }
  2220. else
  2221. {
  2222. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  2223. server_print_usage(argv[0], default_params, default_sparams);
  2224. exit(1);
  2225. }
  2226. }
  2227. if (!params.kv_overrides.empty()) {
  2228. params.kv_overrides.emplace_back(llama_model_kv_override());
  2229. params.kv_overrides.back().key[0] = 0;
  2230. }
  2231. if (invalid_param)
  2232. {
  2233. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  2234. server_print_usage(argv[0], default_params, default_sparams);
  2235. exit(1);
  2236. }
  2237. }
  2238. static std::string random_string()
  2239. {
  2240. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  2241. std::random_device rd;
  2242. std::mt19937 generator(rd());
  2243. std::string result(32, ' ');
  2244. for (int i = 0; i < 32; ++i) {
  2245. result[i] = str[generator() % str.size()];
  2246. }
  2247. return result;
  2248. }
  2249. static std::string gen_chatcmplid()
  2250. {
  2251. std::stringstream chatcmplid;
  2252. chatcmplid << "chatcmpl-" << random_string();
  2253. return chatcmplid.str();
  2254. }
  2255. std::string format_chatml(std::vector<json> messages)
  2256. {
  2257. std::ostringstream chatml_msgs;
  2258. for (auto it = messages.begin(); it != messages.end(); ++it) {
  2259. chatml_msgs << "<|im_start|>"
  2260. << json_value(*it, "role", std::string("user")) << '\n';
  2261. chatml_msgs << json_value(*it, "content", std::string(""))
  2262. << "<|im_end|>\n";
  2263. }
  2264. chatml_msgs << "<|im_start|>assistant" << '\n';
  2265. return chatml_msgs.str();
  2266. }
  2267. /* llama.cpp completion api semantics */
  2268. json oaicompat_completion_params_parse(
  2269. const json &body /* openai api json semantics */)
  2270. {
  2271. json llama_params;
  2272. llama_params["__oaicompat"] = true;
  2273. // Map OpenAI parameters to llama.cpp parameters
  2274. //
  2275. // For parameters that are defined by the OpenAI documentation (e.g.
  2276. // temperature), we explicitly specify OpenAI's intended default; we
  2277. // need to do that because sometimes OpenAI disagrees with llama.cpp
  2278. //
  2279. // https://platform.openai.com/docs/api-reference/chat/create
  2280. llama_sampling_params default_sparams;
  2281. llama_params["model"] = json_value(body, "model", std::string("unknown"));
  2282. llama_params["prompt"] = format_chatml(body["messages"]); // OpenAI 'messages' to llama.cpp 'prompt'
  2283. llama_params["cache_prompt"] = json_value(body, "cache_prompt", false);
  2284. llama_params["temperature"] = json_value(body, "temperature", 0.0);
  2285. llama_params["top_k"] = json_value(body, "top_k", default_sparams.top_k);
  2286. llama_params["top_p"] = json_value(body, "top_p", 1.0);
  2287. llama_params["n_predict"] = json_value(body, "max_tokens", -1);
  2288. llama_params["logit_bias"] = json_value(body, "logit_bias",json::object());
  2289. llama_params["frequency_penalty"] = json_value(body, "frequency_penalty", 0.0);
  2290. llama_params["presence_penalty"] = json_value(body, "presence_penalty", 0.0);
  2291. llama_params["seed"] = json_value(body, "seed", LLAMA_DEFAULT_SEED);
  2292. llama_params["stream"] = json_value(body, "stream", false);
  2293. llama_params["mirostat"] = json_value(body, "mirostat", default_sparams.mirostat);
  2294. llama_params["mirostat_tau"] = json_value(body, "mirostat_tau", default_sparams.mirostat_tau);
  2295. llama_params["mirostat_eta"] = json_value(body, "mirostat_eta", default_sparams.mirostat_eta);
  2296. llama_params["penalize_nl"] = json_value(body, "penalize_nl", default_sparams.penalize_nl);
  2297. llama_params["typical_p"] = json_value(body, "typical_p", default_sparams.typical_p);
  2298. llama_params["repeat_last_n"] = json_value(body, "repeat_last_n", default_sparams.penalty_last_n);
  2299. llama_params["ignore_eos"] = json_value(body, "ignore_eos", false);
  2300. llama_params["tfs_z"] = json_value(body, "tfs_z", default_sparams.tfs_z);
  2301. if (body.count("grammar") != 0) {
  2302. llama_params["grammar"] = json_value(body, "grammar", json::object());
  2303. }
  2304. // Handle 'stop' field
  2305. if (body.contains("stop") && body["stop"].is_string()) {
  2306. llama_params["stop"] = json::array({body["stop"].get<std::string>()});
  2307. } else {
  2308. llama_params["stop"] = json_value(body, "stop", json::array());
  2309. }
  2310. // Ensure there is ChatML-specific end sequence among stop words
  2311. llama_params["stop"].push_back("<|im_end|>");
  2312. return llama_params;
  2313. }
  2314. static json format_final_response_oaicompat(const json &request, const task_result &response, bool streaming = false)
  2315. {
  2316. json result = response.result_json;
  2317. bool stopped_word = result.count("stopped_word") != 0;
  2318. bool stopped_eos = json_value(result, "stopped_eos", false);
  2319. int num_tokens_predicted = json_value(result, "tokens_predicted", 0);
  2320. int num_prompt_tokens = json_value(result, "tokens_evaluated", 0);
  2321. std::string content = json_value(result, "content", std::string(""));
  2322. std::string finish_reason = "length";
  2323. if (stopped_word || stopped_eos) {
  2324. finish_reason = "stop";
  2325. }
  2326. json choices =
  2327. streaming ? json::array({json{{"finish_reason", finish_reason},
  2328. {"index", 0},
  2329. {"delta", json::object()}}})
  2330. : json::array({json{{"finish_reason", finish_reason},
  2331. {"index", 0},
  2332. {"message", json{{"content", content},
  2333. {"role", "assistant"}}}}});
  2334. std::time_t t = std::time(0);
  2335. json res =
  2336. json{{"choices", choices},
  2337. {"created", t},
  2338. {"model",
  2339. json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  2340. {"object", streaming ? "chat.completion.chunk" : "chat.completion"},
  2341. {"usage",
  2342. json{{"completion_tokens", num_tokens_predicted},
  2343. {"prompt_tokens", num_prompt_tokens},
  2344. {"total_tokens", num_tokens_predicted + num_prompt_tokens}}},
  2345. {"id", gen_chatcmplid()}};
  2346. if (server_verbose) {
  2347. res["__verbose"] = result;
  2348. }
  2349. if (result.contains("completion_probabilities")) {
  2350. res["completion_probabilities"] = json_value(result, "completion_probabilities", json::array());
  2351. }
  2352. return res;
  2353. }
  2354. // return value is vector as there is one case where we might need to generate two responses
  2355. static std::vector<json> format_partial_response_oaicompat(const task_result &response) {
  2356. json result = response.result_json;
  2357. if (!result.contains("model") || !result.contains("oaicompat_token_ctr")) {
  2358. return std::vector<json>({response.result_json});
  2359. }
  2360. bool first = json_value(result, "oaicompat_token_ctr", 0) == 0;
  2361. std::string modelname = json_value(result, "model", std::string(DEFAULT_OAICOMPAT_MODEL));
  2362. bool stopped_word = json_value(result, "stopped_word", false);
  2363. bool stopped_eos = json_value(result, "stopped_eos", false);
  2364. bool stopped_limit = json_value(result, "stopped_limit", false);
  2365. std::string content = json_value(result, "content", std::string(""));
  2366. std::string finish_reason;
  2367. if (stopped_word || stopped_eos) {
  2368. finish_reason = "stop";
  2369. }
  2370. if (stopped_limit) {
  2371. finish_reason = "length";
  2372. }
  2373. std::time_t t = std::time(0);
  2374. json choices;
  2375. if (!finish_reason.empty()) {
  2376. choices = json::array({json{{"finish_reason", finish_reason},
  2377. {"index", 0},
  2378. {"delta", json::object()}}});
  2379. } else {
  2380. if (first) {
  2381. if (content.empty()) {
  2382. choices = json::array({json{{"finish_reason", nullptr},
  2383. {"index", 0},
  2384. {"delta", json{{"role", "assistant"}}}}});
  2385. } else {
  2386. // We have to send this as two updates to conform to openai behavior
  2387. json initial_ret = json{{"choices", json::array({json{
  2388. {"finish_reason", nullptr},
  2389. {"index", 0},
  2390. {"delta", json{
  2391. {"role", "assistant"}
  2392. }}}})},
  2393. {"created", t},
  2394. {"id", gen_chatcmplid()},
  2395. {"model", modelname},
  2396. {"object", "chat.completion.chunk"}};
  2397. json second_ret = json{
  2398. {"choices", json::array({json{{"finish_reason", nullptr},
  2399. {"index", 0},
  2400. {"delta", json{
  2401. {"content", content}}}
  2402. }})},
  2403. {"created", t},
  2404. {"id", gen_chatcmplid()},
  2405. {"model", modelname},
  2406. {"object", "chat.completion.chunk"}};
  2407. return std::vector<json>({initial_ret, second_ret});
  2408. }
  2409. } else {
  2410. // Some idiosyncrasy in task processing logic makes several trailing calls
  2411. // with empty content, we ignore these at the calee site.
  2412. if (content.empty()) {
  2413. return std::vector<json>({json::object()});
  2414. }
  2415. choices = json::array({json{
  2416. {"finish_reason", nullptr},
  2417. {"index", 0},
  2418. {"delta",
  2419. json{
  2420. {"content", content},
  2421. }},
  2422. }});
  2423. }
  2424. }
  2425. json ret = json{{"choices", choices},
  2426. {"created", t},
  2427. {"id", gen_chatcmplid()},
  2428. {"model", modelname},
  2429. {"object", "chat.completion.chunk"}};
  2430. return std::vector<json>({ret});
  2431. }
  2432. static json format_partial_response(
  2433. llama_server_context &llama, llama_client_slot *slot, const std::string &content, const std::vector<completion_token_output> &probs
  2434. ) {
  2435. json res = json
  2436. {
  2437. {"content", content },
  2438. {"stop", false},
  2439. {"slot_id", slot->id },
  2440. {"multimodal", llama.multimodal }
  2441. };
  2442. if (slot->sparams.n_probs > 0)
  2443. {
  2444. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  2445. }
  2446. return res;
  2447. }
  2448. static json format_tokenizer_response(const std::vector<llama_token> &tokens)
  2449. {
  2450. return json{
  2451. {"tokens", tokens}};
  2452. }
  2453. static json format_detokenized_response(std::string content)
  2454. {
  2455. return json{
  2456. {"content", content}};
  2457. }
  2458. static void log_server_request(const httplib::Request &req, const httplib::Response &res)
  2459. {
  2460. LOG_INFO("request", {
  2461. {"remote_addr", req.remote_addr},
  2462. {"remote_port", req.remote_port},
  2463. {"status", res.status},
  2464. {"method", req.method},
  2465. {"path", req.path},
  2466. {"params", req.params},
  2467. });
  2468. LOG_VERBOSE("request", {
  2469. {"request", req.body},
  2470. {"response", res.body},
  2471. });
  2472. }
  2473. struct token_translator
  2474. {
  2475. llama_context * ctx;
  2476. std::string operator()(llama_token tok) const { return llama_token_to_piece(ctx, tok); }
  2477. std::string operator()(const completion_token_output &cto) const { return (*this)(cto.tok); }
  2478. };
  2479. static void append_to_generated_text_from_generated_token_probs(llama_server_context &llama, llama_client_slot *slot)
  2480. {
  2481. auto & gtps = slot->generated_token_probs;
  2482. auto translator = token_translator{llama.ctx};
  2483. auto add_strlen = [=](size_t sum, const completion_token_output & cto) { return sum + translator(cto).size(); };
  2484. const size_t len = std::accumulate(gtps.begin(), gtps.end(), size_t(0), add_strlen);
  2485. if (slot->generated_text.capacity() < slot->generated_text.size() + len)
  2486. {
  2487. slot->generated_text.reserve(slot->generated_text.size() + len);
  2488. }
  2489. for (const completion_token_output & cto : gtps)
  2490. {
  2491. slot->generated_text += translator(cto);
  2492. }
  2493. }
  2494. int main(int argc, char **argv)
  2495. {
  2496. #if SERVER_VERBOSE != 1
  2497. log_disable();
  2498. #endif
  2499. // own arguments required by this example
  2500. gpt_params params;
  2501. server_params sparams;
  2502. // struct that contains llama context and inference
  2503. llama_server_context llama;
  2504. server_params_parse(argc, argv, sparams, params, llama);
  2505. if (params.model_alias == "unknown")
  2506. {
  2507. params.model_alias = params.model;
  2508. }
  2509. llama_backend_init(params.numa);
  2510. LOG_INFO("build info", {{"build", LLAMA_BUILD_NUMBER},
  2511. {"commit", LLAMA_COMMIT}});
  2512. LOG_INFO("system info", {
  2513. {"n_threads", params.n_threads},
  2514. {"n_threads_batch", params.n_threads_batch},
  2515. {"total_threads", std::thread::hardware_concurrency()},
  2516. {"system_info", llama_print_system_info()},
  2517. });
  2518. httplib::Server svr;
  2519. std::atomic<server_state> state{SERVER_STATE_LOADING_MODEL};
  2520. svr.set_default_headers({{"Server", "llama.cpp"}});
  2521. // CORS preflight
  2522. svr.Options(R"(.*)", [](const httplib::Request &req, httplib::Response &res) {
  2523. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2524. res.set_header("Access-Control-Allow-Credentials", "true");
  2525. res.set_header("Access-Control-Allow-Methods", "POST");
  2526. res.set_header("Access-Control-Allow-Headers", "*");
  2527. });
  2528. svr.Get("/health", [&](const httplib::Request&, httplib::Response& res) {
  2529. server_state current_state = state.load();
  2530. switch(current_state) {
  2531. case SERVER_STATE_READY:
  2532. res.set_content(R"({"status": "ok"})", "application/json");
  2533. res.status = 200; // HTTP OK
  2534. break;
  2535. case SERVER_STATE_LOADING_MODEL:
  2536. res.set_content(R"({"status": "loading model"})", "application/json");
  2537. res.status = 503; // HTTP Service Unavailable
  2538. break;
  2539. case SERVER_STATE_ERROR:
  2540. res.set_content(R"({"status": "error", "error": "Model failed to load"})", "application/json");
  2541. res.status = 500; // HTTP Internal Server Error
  2542. break;
  2543. }
  2544. });
  2545. svr.set_logger(log_server_request);
  2546. svr.set_exception_handler([](const httplib::Request &, httplib::Response &res, std::exception_ptr ep)
  2547. {
  2548. const char fmt[] = "500 Internal Server Error\n%s";
  2549. char buf[BUFSIZ];
  2550. try
  2551. {
  2552. std::rethrow_exception(std::move(ep));
  2553. }
  2554. catch (std::exception &e)
  2555. {
  2556. snprintf(buf, sizeof(buf), fmt, e.what());
  2557. }
  2558. catch (...)
  2559. {
  2560. snprintf(buf, sizeof(buf), fmt, "Unknown Exception");
  2561. }
  2562. res.set_content(buf, "text/plain; charset=utf-8");
  2563. res.status = 500;
  2564. });
  2565. svr.set_error_handler([](const httplib::Request &, httplib::Response &res)
  2566. {
  2567. if (res.status == 401)
  2568. {
  2569. res.set_content("Unauthorized", "text/plain; charset=utf-8");
  2570. }
  2571. if (res.status == 400)
  2572. {
  2573. res.set_content("Invalid request", "text/plain; charset=utf-8");
  2574. }
  2575. else if (res.status == 404)
  2576. {
  2577. res.set_content("File Not Found", "text/plain; charset=utf-8");
  2578. res.status = 404;
  2579. }
  2580. });
  2581. // set timeouts and change hostname and port
  2582. svr.set_read_timeout (sparams.read_timeout);
  2583. svr.set_write_timeout(sparams.write_timeout);
  2584. if (!svr.bind_to_port(sparams.hostname, sparams.port))
  2585. {
  2586. fprintf(stderr, "\ncouldn't bind to server socket: hostname=%s port=%d\n\n", sparams.hostname.c_str(), sparams.port);
  2587. return 1;
  2588. }
  2589. // Set the base directory for serving static files
  2590. svr.set_base_dir(sparams.public_path);
  2591. // to make it ctrl+clickable:
  2592. LOG_TEE("\nllama server listening at http://%s:%d\n\n", sparams.hostname.c_str(), sparams.port);
  2593. std::unordered_map<std::string, std::string> log_data;
  2594. log_data["hostname"] = sparams.hostname;
  2595. log_data["port"] = std::to_string(sparams.port);
  2596. if (sparams.api_keys.size() == 1) {
  2597. log_data["api_key"] = "api_key: ****" + sparams.api_keys[0].substr(sparams.api_keys[0].length() - 4);
  2598. } else if (sparams.api_keys.size() > 1) {
  2599. log_data["api_key"] = "api_key: " + std::to_string(sparams.api_keys.size()) + " keys loaded";
  2600. }
  2601. LOG_INFO("HTTP server listening", log_data);
  2602. // run the HTTP server in a thread - see comment below
  2603. std::thread t([&]()
  2604. {
  2605. if (!svr.listen_after_bind())
  2606. {
  2607. state.store(SERVER_STATE_ERROR);
  2608. return 1;
  2609. }
  2610. return 0;
  2611. });
  2612. // load the model
  2613. if (!llama.load_model(params))
  2614. {
  2615. state.store(SERVER_STATE_ERROR);
  2616. return 1;
  2617. } else {
  2618. llama.initialize();
  2619. state.store(SERVER_STATE_READY);
  2620. LOG_INFO("model loaded", {});
  2621. }
  2622. // Middleware for API key validation
  2623. auto validate_api_key = [&sparams](const httplib::Request &req, httplib::Response &res) -> bool {
  2624. // If API key is not set, skip validation
  2625. if (sparams.api_keys.empty()) {
  2626. return true;
  2627. }
  2628. // Check for API key in the header
  2629. auto auth_header = req.get_header_value("Authorization");
  2630. std::string prefix = "Bearer ";
  2631. if (auth_header.substr(0, prefix.size()) == prefix) {
  2632. std::string received_api_key = auth_header.substr(prefix.size());
  2633. if (std::find(sparams.api_keys.begin(), sparams.api_keys.end(), received_api_key) != sparams.api_keys.end()) {
  2634. return true; // API key is valid
  2635. }
  2636. }
  2637. // API key is invalid or not provided
  2638. res.set_content("Unauthorized: Invalid API Key", "text/plain; charset=utf-8");
  2639. res.status = 401; // Unauthorized
  2640. LOG_WARNING("Unauthorized: Invalid API Key", {});
  2641. return false;
  2642. };
  2643. // this is only called if no index.html is found in the public --path
  2644. svr.Get("/", [](const httplib::Request &, httplib::Response &res)
  2645. {
  2646. res.set_content(reinterpret_cast<const char*>(&index_html), index_html_len, "text/html; charset=utf-8");
  2647. return false;
  2648. });
  2649. // this is only called if no index.js is found in the public --path
  2650. svr.Get("/index.js", [](const httplib::Request &, httplib::Response &res)
  2651. {
  2652. res.set_content(reinterpret_cast<const char *>(&index_js), index_js_len, "text/javascript; charset=utf-8");
  2653. return false;
  2654. });
  2655. // this is only called if no index.html is found in the public --path
  2656. svr.Get("/completion.js", [](const httplib::Request &, httplib::Response &res)
  2657. {
  2658. res.set_content(reinterpret_cast<const char*>(&completion_js), completion_js_len, "application/javascript; charset=utf-8");
  2659. return false;
  2660. });
  2661. // this is only called if no index.html is found in the public --path
  2662. svr.Get("/json-schema-to-grammar.mjs", [](const httplib::Request &, httplib::Response &res)
  2663. {
  2664. res.set_content(reinterpret_cast<const char*>(&json_schema_to_grammar_mjs), json_schema_to_grammar_mjs_len, "application/javascript; charset=utf-8");
  2665. return false;
  2666. });
  2667. svr.Get("/props", [&llama](const httplib::Request & req, httplib::Response &res)
  2668. {
  2669. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2670. json data = {
  2671. { "user_name", llama.name_user.c_str() },
  2672. { "assistant_name", llama.name_assistant.c_str() }
  2673. };
  2674. res.set_content(data.dump(), "application/json; charset=utf-8");
  2675. });
  2676. svr.Post("/completion", [&llama, &validate_api_key](const httplib::Request &req, httplib::Response &res)
  2677. {
  2678. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2679. if (!validate_api_key(req, res)) {
  2680. return;
  2681. }
  2682. json data = json::parse(req.body);
  2683. const int task_id = llama.request_completion(data, false, false, -1);
  2684. if (!json_value(data, "stream", false)) {
  2685. std::string completion_text;
  2686. task_result result = llama.next_result(task_id);
  2687. if (!result.error && result.stop) {
  2688. res.set_content(result.result_json.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  2689. }
  2690. else
  2691. {
  2692. res.status = 404;
  2693. res.set_content(result.result_json["content"], "text/plain; charset=utf-8");
  2694. return;
  2695. }
  2696. } else {
  2697. const auto chunked_content_provider = [task_id, &llama](size_t, httplib::DataSink & sink)
  2698. {
  2699. while (true)
  2700. {
  2701. task_result result = llama.next_result(task_id);
  2702. if (!result.error) {
  2703. const std::string str =
  2704. "data: " +
  2705. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace) +
  2706. "\n\n";
  2707. LOG_VERBOSE("data stream", {
  2708. { "to_send", str }
  2709. });
  2710. if (!sink.write(str.c_str(), str.size()))
  2711. {
  2712. return false;
  2713. }
  2714. if (result.stop) {
  2715. break;
  2716. }
  2717. } else {
  2718. const std::string str =
  2719. "error: " +
  2720. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace) +
  2721. "\n\n";
  2722. LOG_VERBOSE("data stream", {
  2723. { "to_send", str }
  2724. });
  2725. if (!sink.write(str.c_str(), str.size()))
  2726. {
  2727. return false;
  2728. }
  2729. break;
  2730. }
  2731. }
  2732. sink.done();
  2733. return true;
  2734. };
  2735. auto on_complete = [task_id, &llama] (bool)
  2736. {
  2737. // cancel
  2738. llama.request_cancel(task_id);
  2739. };
  2740. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2741. }
  2742. });
  2743. svr.Get("/v1/models", [&params](const httplib::Request& req, httplib::Response& res)
  2744. {
  2745. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2746. std::time_t t = std::time(0);
  2747. json models = {
  2748. {"object", "list"},
  2749. {"data", {
  2750. {
  2751. {"id", params.model_alias},
  2752. {"object", "model"},
  2753. {"created", t},
  2754. {"owned_by", "llamacpp"}
  2755. },
  2756. }}
  2757. };
  2758. res.set_content(models.dump(), "application/json; charset=utf-8");
  2759. });
  2760. // TODO: add mount point without "/v1" prefix -- how?
  2761. svr.Post("/v1/chat/completions", [&llama, &validate_api_key](const httplib::Request &req, httplib::Response &res)
  2762. {
  2763. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2764. if (!validate_api_key(req, res)) {
  2765. return;
  2766. }
  2767. json data = oaicompat_completion_params_parse(json::parse(req.body));
  2768. const int task_id = llama.request_completion(data, false, false, -1);
  2769. if (!json_value(data, "stream", false)) {
  2770. std::string completion_text;
  2771. task_result result = llama.next_result(task_id);
  2772. if (!result.error && result.stop) {
  2773. json oaicompat_result = format_final_response_oaicompat(data, result);
  2774. res.set_content(oaicompat_result.dump(-1, ' ', false,
  2775. json::error_handler_t::replace),
  2776. "application/json; charset=utf-8");
  2777. } else {
  2778. res.status = 500;
  2779. res.set_content(result.result_json["content"], "text/plain; charset=utf-8");
  2780. return;
  2781. }
  2782. } else {
  2783. const auto chunked_content_provider = [task_id, &llama](size_t, httplib::DataSink &sink) {
  2784. while (true) {
  2785. task_result llama_result = llama.next_result(task_id);
  2786. if (!llama_result.error) {
  2787. std::vector<json> result_array = format_partial_response_oaicompat( llama_result);
  2788. for (auto it = result_array.begin(); it != result_array.end(); ++it)
  2789. {
  2790. if (!it->empty()) {
  2791. const std::string str =
  2792. "data: " +
  2793. it->dump(-1, ' ', false, json::error_handler_t::replace) +
  2794. "\n\n";
  2795. LOG_VERBOSE("data stream", {{"to_send", str}});
  2796. if (!sink.write(str.c_str(), str.size())) {
  2797. return false;
  2798. }
  2799. }
  2800. }
  2801. if (llama_result.stop) {
  2802. break;
  2803. }
  2804. } else {
  2805. const std::string str =
  2806. "error: " +
  2807. llama_result.result_json.dump(-1, ' ', false,
  2808. json::error_handler_t::replace) +
  2809. "\n\n";
  2810. LOG_VERBOSE("data stream", {{"to_send", str}});
  2811. if (!sink.write(str.c_str(), str.size())) {
  2812. return false;
  2813. }
  2814. break;
  2815. }
  2816. }
  2817. sink.done();
  2818. return true;
  2819. };
  2820. auto on_complete = [task_id, &llama](bool) {
  2821. // cancel request
  2822. llama.request_cancel(task_id);
  2823. };
  2824. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2825. }
  2826. });
  2827. svr.Post("/infill", [&llama, &validate_api_key](const httplib::Request &req, httplib::Response &res)
  2828. {
  2829. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2830. if (!validate_api_key(req, res)) {
  2831. return;
  2832. }
  2833. json data = json::parse(req.body);
  2834. const int task_id = llama.request_completion(data, true, false, -1);
  2835. if (!json_value(data, "stream", false)) {
  2836. std::string completion_text;
  2837. task_result result = llama.next_result(task_id);
  2838. if (!result.error && result.stop)
  2839. {
  2840. res.set_content(result.result_json.dump(-1, ' ', false, json::error_handler_t::replace), "application/json; charset=utf-8");
  2841. }
  2842. else
  2843. {
  2844. res.status = 404;
  2845. res.set_content(result.result_json["content"], "text/plain; charset=utf-8");
  2846. return;
  2847. }
  2848. } else {
  2849. const auto chunked_content_provider = [task_id, &llama](size_t, httplib::DataSink & sink) {
  2850. while (true)
  2851. {
  2852. task_result result = llama.next_result(task_id);
  2853. if (!result.error) {
  2854. const std::string str =
  2855. "data: " +
  2856. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace) +
  2857. "\n\n";
  2858. LOG_VERBOSE("data stream", {
  2859. { "to_send", str }
  2860. });
  2861. if (!sink.write(str.c_str(), str.size()))
  2862. {
  2863. return false;
  2864. }
  2865. if (result.stop)
  2866. {
  2867. break;
  2868. }
  2869. }
  2870. else
  2871. {
  2872. break;
  2873. }
  2874. }
  2875. sink.done();
  2876. return true;
  2877. };
  2878. auto on_complete = [task_id, &llama] (bool)
  2879. {
  2880. // cancel
  2881. llama.request_cancel(task_id);
  2882. };
  2883. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2884. }
  2885. });
  2886. svr.Get("/model.json", [&llama](const httplib::Request &, httplib::Response &res)
  2887. {
  2888. const json data = llama.get_model_props();
  2889. return res.set_content(data.dump(), "application/json; charset=utf-8");
  2890. });
  2891. svr.Options(R"(/.*)", [](const httplib::Request &, httplib::Response &res)
  2892. { return res.set_content("", "application/json; charset=utf-8"); });
  2893. svr.Post("/tokenize", [&llama](const httplib::Request &req, httplib::Response &res)
  2894. {
  2895. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2896. const json body = json::parse(req.body);
  2897. std::vector<llama_token> tokens;
  2898. if (body.count("content") != 0)
  2899. {
  2900. tokens = llama.tokenize(body["content"], false);
  2901. }
  2902. const json data = format_tokenizer_response(tokens);
  2903. return res.set_content(data.dump(), "application/json; charset=utf-8");
  2904. });
  2905. svr.Post("/detokenize", [&llama](const httplib::Request &req, httplib::Response &res)
  2906. {
  2907. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2908. const json body = json::parse(req.body);
  2909. std::string content;
  2910. if (body.count("tokens") != 0)
  2911. {
  2912. const std::vector<llama_token> tokens = body["tokens"];
  2913. content = tokens_to_str(llama.ctx, tokens.cbegin(), tokens.cend());
  2914. }
  2915. const json data = format_detokenized_response(content);
  2916. return res.set_content(data.dump(), "application/json; charset=utf-8");
  2917. });
  2918. svr.Post("/embedding", [&llama](const httplib::Request &req, httplib::Response &res)
  2919. {
  2920. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2921. const json body = json::parse(req.body);
  2922. json prompt;
  2923. if (body.count("content") != 0)
  2924. {
  2925. prompt = body["content"];
  2926. }
  2927. else
  2928. {
  2929. prompt = "";
  2930. }
  2931. json image_data;
  2932. if (body.count("image_data") != 0) {
  2933. image_data = body["image_data"];
  2934. }
  2935. else
  2936. {
  2937. image_data = "";
  2938. }
  2939. const int task_id = llama.request_completion({ {"prompt", prompt}, { "n_predict", 0}, {"image_data", image_data} }, false, true, -1);
  2940. task_result result = llama.next_result(task_id);
  2941. return res.set_content(result.result_json.dump(), "application/json; charset=utf-8");
  2942. });
  2943. // GG: if I put the main loop inside a thread, it crashes on the first request when build in Debug!?
  2944. // "Bus error: 10" - this is on macOS, it does not crash on Linux
  2945. //std::thread t2([&]()
  2946. {
  2947. bool running = true;
  2948. while (running)
  2949. {
  2950. running = llama.update_slots();
  2951. }
  2952. }
  2953. //);
  2954. t.join();
  2955. llama_backend_free();
  2956. return 0;
  2957. }