server.cpp 118 KB

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