server.cpp 122 KB

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