server.cpp 111 KB

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