1
0

server.cpp 117 KB

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