server.cpp 154 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948
  1. #include "utils.hpp"
  2. #include "arg.h"
  3. #include "common.h"
  4. #include "json-schema-to-grammar.h"
  5. #include "llama.h"
  6. #include "log.h"
  7. #include "sampling.h"
  8. #include "speculative.h"
  9. // Change JSON_ASSERT from assert() to GGML_ASSERT:
  10. #define JSON_ASSERT GGML_ASSERT
  11. #include "json.hpp"
  12. // mime type for sending response
  13. #define MIMETYPE_JSON "application/json; charset=utf-8"
  14. // auto generated files (update with ./deps.sh)
  15. #include "index.html.hpp"
  16. #include "loading.html.hpp"
  17. #include <atomic>
  18. #include <condition_variable>
  19. #include <cstddef>
  20. #include <cinttypes>
  21. #include <deque>
  22. #include <memory>
  23. #include <mutex>
  24. #include <signal.h>
  25. #include <thread>
  26. #include <unordered_map>
  27. #include <unordered_set>
  28. using json = nlohmann::ordered_json;
  29. enum stop_type {
  30. STOP_TYPE_NONE,
  31. STOP_TYPE_EOS,
  32. STOP_TYPE_WORD,
  33. STOP_TYPE_LIMIT,
  34. };
  35. // state diagram: https://github.com/ggerganov/llama.cpp/pull/9283
  36. enum slot_state {
  37. SLOT_STATE_IDLE,
  38. SLOT_STATE_STARTED, // TODO: this state is only used for setting up the initial prompt processing; maybe merge it with launch_slot_with_task in the future
  39. SLOT_STATE_PROCESSING_PROMPT,
  40. SLOT_STATE_DONE_PROMPT,
  41. SLOT_STATE_GENERATING,
  42. };
  43. enum server_state {
  44. SERVER_STATE_LOADING_MODEL, // Server is starting up, model not fully loaded yet
  45. SERVER_STATE_READY, // Server is ready and model is loaded
  46. };
  47. enum server_task_type {
  48. SERVER_TASK_TYPE_INFERENCE,
  49. SERVER_TASK_TYPE_CANCEL,
  50. SERVER_TASK_TYPE_NEXT_RESPONSE,
  51. SERVER_TASK_TYPE_METRICS,
  52. SERVER_TASK_TYPE_SLOT_SAVE,
  53. SERVER_TASK_TYPE_SLOT_RESTORE,
  54. SERVER_TASK_TYPE_SLOT_ERASE,
  55. SERVER_TASK_TYPE_SET_LORA,
  56. };
  57. enum server_task_inf_type {
  58. SERVER_TASK_INF_TYPE_COMPLETION,
  59. SERVER_TASK_INF_TYPE_EMBEDDING,
  60. SERVER_TASK_INF_TYPE_RERANK,
  61. SERVER_TASK_INF_TYPE_INFILL,
  62. };
  63. // https://community.openai.com/t/openai-chat-list-of-error-codes-and-types/357791/11
  64. enum error_type {
  65. ERROR_TYPE_INVALID_REQUEST,
  66. ERROR_TYPE_AUTHENTICATION,
  67. ERROR_TYPE_SERVER,
  68. ERROR_TYPE_NOT_FOUND,
  69. ERROR_TYPE_PERMISSION,
  70. ERROR_TYPE_UNAVAILABLE, // custom error
  71. ERROR_TYPE_NOT_SUPPORTED, // custom error
  72. };
  73. struct server_task {
  74. int id = -1; // to be filled by server_queue
  75. int id_target = -1; // used by SERVER_TASK_TYPE_CANCEL
  76. llama_tokens prompt_tokens;
  77. server_task_type type;
  78. // TODO @ngxson : we should get rid of json type here
  79. json data;
  80. server_task_inf_type inf_type = SERVER_TASK_INF_TYPE_COMPLETION;
  81. // utility function
  82. static std::unordered_set<int> get_list_id(const std::vector<server_task> & tasks) {
  83. std::unordered_set<int> ids(tasks.size());
  84. for (size_t i = 0; i < tasks.size(); i++) {
  85. ids.insert(tasks[i].id);
  86. }
  87. return ids;
  88. }
  89. };
  90. struct slot_params {
  91. bool stream = true;
  92. bool cache_prompt = true; // remember the prompt to avoid reprocessing all prompt
  93. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  94. int32_t n_discard = 0; // number of tokens after n_keep that may be discarded when shifting context, 0 defaults to half
  95. int32_t n_predict = -1; // new tokens to predict
  96. int32_t n_indent = 0; // mininum line indentation for the generated text in number of whitespace characters
  97. int64_t t_max_prompt_ms = -1; // TODO: implement
  98. int64_t t_max_predict_ms = -1; // if positive, limit the generation phase to this time limit
  99. std::vector<std::string> antiprompt;
  100. bool timings_per_token = false;
  101. struct common_params_sampling sampling;
  102. struct common_params_speculative speculative;
  103. // params only used in to_json()
  104. int32_t n_ctx;
  105. uint32_t seed_cur;
  106. bool can_speculative;
  107. // OAI-compat fields
  108. bool verbose = false;
  109. bool oaicompat = false;
  110. bool oaicompat_chat = true;
  111. std::string oaicompat_model;
  112. std::string oaicompat_cmpl_id;
  113. json to_json() {
  114. std::vector<std::string> samplers;
  115. samplers.reserve(sampling.samplers.size());
  116. for (const auto & sampler : sampling.samplers) {
  117. samplers.emplace_back(common_sampler_type_to_str(sampler));
  118. }
  119. return json {
  120. {"n_ctx", n_ctx},
  121. {"n_predict", n_predict}, // Server configured n_predict
  122. {"temperature", sampling.temp},
  123. {"dynatemp_range", sampling.dynatemp_range},
  124. {"dynatemp_exponent", sampling.dynatemp_exponent},
  125. {"top_k", sampling.top_k},
  126. {"top_p", sampling.top_p},
  127. {"min_p", sampling.min_p},
  128. {"xtc_probability", sampling.xtc_probability},
  129. {"xtc_threshold", sampling.xtc_threshold},
  130. {"typical_p", sampling.typ_p},
  131. {"repeat_last_n", sampling.penalty_last_n},
  132. {"repeat_penalty", sampling.penalty_repeat},
  133. {"presence_penalty", sampling.penalty_present},
  134. {"frequency_penalty", sampling.penalty_freq},
  135. {"dry_multiplier", sampling.dry_multiplier},
  136. {"dry_base", sampling.dry_base},
  137. {"dry_allowed_length", sampling.dry_allowed_length},
  138. {"dry_penalty_last_n", sampling.dry_penalty_last_n},
  139. {"dry_sequence_breakers", sampling.dry_sequence_breakers},
  140. {"mirostat", sampling.mirostat},
  141. {"mirostat_tau", sampling.mirostat_tau},
  142. {"mirostat_eta", sampling.mirostat_eta},
  143. {"penalize_nl", sampling.penalize_nl},
  144. {"stop", antiprompt},
  145. {"max_tokens", n_predict}, // User configured n_predict
  146. {"n_keep", n_keep},
  147. {"n_discard", n_discard},
  148. {"ignore_eos", sampling.ignore_eos},
  149. {"stream", stream},
  150. //{"logit_bias", sampling.logit_bias},
  151. {"n_probs", sampling.n_probs},
  152. {"min_keep", sampling.min_keep},
  153. {"grammar", sampling.grammar},
  154. {"samplers", samplers},
  155. {"speculative", can_speculative},
  156. {"speculative.n_max", speculative.n_max},
  157. {"speculative.n_min", speculative.n_min},
  158. {"speculative.p_min", speculative.p_min},
  159. {"timings_per_token", timings_per_token},
  160. };
  161. }
  162. };
  163. struct result_timings {
  164. int32_t prompt_n = -1;
  165. double prompt_ms;
  166. double prompt_per_token_ms;
  167. double prompt_per_second;
  168. int32_t predicted_n = -1;
  169. double predicted_ms;
  170. double predicted_per_token_ms;
  171. double predicted_per_second;
  172. json to_json() {
  173. return {
  174. {"prompt_n", prompt_n},
  175. {"prompt_ms", prompt_ms},
  176. {"prompt_per_token_ms", prompt_per_token_ms},
  177. {"prompt_per_second", prompt_per_second},
  178. {"predicted_n", predicted_n},
  179. {"predicted_ms", predicted_ms},
  180. {"predicted_per_token_ms", predicted_per_token_ms},
  181. {"predicted_per_second", predicted_per_second},
  182. };
  183. }
  184. };
  185. struct server_task_result {
  186. int id = -1;
  187. int id_slot = -1;
  188. virtual bool is_error() {
  189. // only used by server_task_result_error
  190. return false;
  191. }
  192. virtual bool is_stop() {
  193. // only used by server_task_result_cmpl_partial
  194. return false;
  195. }
  196. virtual int get_index() {
  197. return -1;
  198. }
  199. virtual json to_json() = 0;
  200. virtual ~server_task_result() = default;
  201. };
  202. // using shared_ptr for polymorphism of server_task_result
  203. using server_task_result_ptr = std::unique_ptr<server_task_result>;
  204. inline std::string stop_type_to_str(stop_type type) {
  205. switch (type) {
  206. case STOP_TYPE_EOS: return "eos";
  207. case STOP_TYPE_WORD: return "word";
  208. case STOP_TYPE_LIMIT: return "limit";
  209. default: return "none";
  210. }
  211. }
  212. struct completion_token_output {
  213. llama_token tok;
  214. std::string text_to_send;
  215. struct token_prob {
  216. llama_token tok;
  217. std::string tok_str;
  218. float prob;
  219. };
  220. std::vector<token_prob> probs;
  221. json to_json() const {
  222. json probs_for_token = json::array();
  223. for (const auto & p : probs) {
  224. probs_for_token.push_back(json {
  225. {"tok_str", p.tok_str},
  226. {"prob", p.prob},
  227. });
  228. }
  229. return probs_for_token;
  230. }
  231. static json probs_vector_to_json(const std::vector<completion_token_output> & probs) {
  232. json out = json::array();
  233. for (const auto & prob : probs) {
  234. const std::string tok_str = prob.text_to_send;
  235. out.push_back(json {
  236. {"content", tok_str},
  237. {"probs", prob.to_json()},
  238. });
  239. }
  240. return out;
  241. }
  242. };
  243. struct server_task_result_cmpl_final : server_task_result {
  244. int index = 0;
  245. std::string content;
  246. bool stream;
  247. result_timings timings;
  248. std::string prompt;
  249. bool truncated;
  250. int32_t n_decoded;
  251. int32_t n_prompt_tokens;
  252. int32_t n_tokens_cached;
  253. int32_t has_new_line;
  254. std::string stopping_word;
  255. stop_type stop = STOP_TYPE_NONE;
  256. std::vector<completion_token_output> probs_output;
  257. slot_params generation_params;
  258. // OAI-compat fields
  259. bool verbose = false;
  260. bool oaicompat = false;
  261. bool oaicompat_chat = true; // TODO: support oaicompat for non-chat
  262. std::string oaicompat_model;
  263. std::string oaicompat_cmpl_id;
  264. virtual int get_index() override {
  265. return index;
  266. }
  267. virtual json to_json() override {
  268. return oaicompat ? to_json_oaicompat_chat() : to_json_non_oaicompat();
  269. }
  270. json to_json_non_oaicompat() {
  271. json res = json {
  272. {"index", index},
  273. {"content", content},
  274. {"id_slot", id_slot},
  275. {"stop", true},
  276. {"model", oaicompat_model},
  277. {"tokens_predicted", n_decoded},
  278. {"tokens_evaluated", n_prompt_tokens},
  279. {"generation_settings", generation_params.to_json()},
  280. {"prompt", prompt},
  281. {"has_new_line", has_new_line},
  282. {"truncated", truncated},
  283. {"stop_type", stop_type_to_str(stop)},
  284. {"stopping_word", stopping_word},
  285. {"tokens_cached", n_tokens_cached},
  286. {"timings", timings.to_json()},
  287. };
  288. if (!probs_output.empty()) {
  289. res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output);
  290. }
  291. return res;
  292. }
  293. json to_json_oaicompat_chat() {
  294. std::string finish_reason = "length";
  295. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  296. finish_reason = "stop";
  297. }
  298. json choices = json::array({json{
  299. {"finish_reason", finish_reason},
  300. {"index", 0},
  301. {"message", json{
  302. {"content", content},
  303. {"role", "assistant"}
  304. }
  305. }}});
  306. std::time_t t = std::time(0);
  307. json res = json {
  308. {"choices", choices},
  309. {"created", t},
  310. {"model", oaicompat_model},
  311. {"object", "chat.completion"},
  312. {"usage", json {
  313. {"completion_tokens", n_decoded},
  314. {"prompt_tokens", n_prompt_tokens},
  315. {"total_tokens", n_decoded + n_prompt_tokens}
  316. }},
  317. {"id", oaicompat_cmpl_id}
  318. };
  319. // extra fields for debugging purposes
  320. if (verbose) {
  321. res["__verbose"] = to_json_non_oaicompat();
  322. }
  323. if (timings.prompt_n >= 0) {
  324. res.push_back({"timings", timings.to_json()});
  325. }
  326. return res;
  327. }
  328. };
  329. struct server_task_result_cmpl_partial : server_task_result {
  330. int index = 0;
  331. std::string content;
  332. bool truncated;
  333. int32_t n_decoded;
  334. int32_t n_prompt_tokens;
  335. stop_type stop = STOP_TYPE_NONE;
  336. std::vector<completion_token_output> probs_output;
  337. result_timings timings;
  338. // OAI-compat fields
  339. bool verbose = false;
  340. bool oaicompat = false;
  341. bool oaicompat_chat = true; // TODO: support oaicompat for non-chat
  342. std::string oaicompat_model;
  343. std::string oaicompat_cmpl_id;
  344. virtual int get_index() override {
  345. return index;
  346. }
  347. virtual bool is_stop() override {
  348. return stop != STOP_TYPE_NONE;
  349. }
  350. virtual json to_json() override {
  351. if (oaicompat) {
  352. return to_json_oaicompat();
  353. }
  354. bool is_stop = stop != STOP_TYPE_NONE;
  355. // non-OAI-compat JSON
  356. json res = json {
  357. {"index", index},
  358. {"content", content},
  359. {"stop_type", stop_type_to_str(stop)},
  360. {"stop", is_stop},
  361. {"id_slot", id_slot},
  362. {"tokens_predicted", n_decoded},
  363. {"tokens_evaluated", n_prompt_tokens},
  364. };
  365. // populate the timings object when needed (usually for the last response or with timings_per_token enabled)
  366. if (timings.prompt_n > 0) {
  367. res.push_back({"timings", timings.to_json()});
  368. }
  369. if (!probs_output.empty()) {
  370. res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output);
  371. }
  372. if (is_stop) {
  373. res.push_back({"truncated", truncated});
  374. }
  375. return res;
  376. }
  377. json to_json_oaicompat() {
  378. bool first = n_decoded == 0;
  379. std::string finish_reason;
  380. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  381. finish_reason = "stop";
  382. } else if (stop == STOP_TYPE_LIMIT) {
  383. finish_reason = "length";
  384. }
  385. std::time_t t = std::time(0);
  386. json choices;
  387. if (!finish_reason.empty()) {
  388. choices = json::array({json{{"finish_reason", finish_reason},
  389. {"index", 0},
  390. {"delta", json::object()}}});
  391. } else {
  392. if (first) {
  393. if (content.empty()) {
  394. choices = json::array({json{{"finish_reason", nullptr},
  395. {"index", 0},
  396. {"delta", json{{"role", "assistant"}}}}});
  397. } else {
  398. // We have to send this as two updates to conform to openai behavior
  399. json initial_ret = json{{"choices", json::array({json{
  400. {"finish_reason", nullptr},
  401. {"index", 0},
  402. {"delta", json{
  403. {"role", "assistant"}
  404. }}}})},
  405. {"created", t},
  406. {"id", oaicompat_cmpl_id},
  407. {"model", oaicompat_model},
  408. {"object", "chat.completion.chunk"}};
  409. json second_ret = json{
  410. {"choices", json::array({json{{"finish_reason", nullptr},
  411. {"index", 0},
  412. {"delta", json{
  413. {"content", content}}}
  414. }})},
  415. {"created", t},
  416. {"id", oaicompat_cmpl_id},
  417. {"model", oaicompat_model},
  418. {"object", "chat.completion.chunk"}};
  419. return std::vector<json>({initial_ret, second_ret});
  420. }
  421. } else {
  422. // Some idiosyncrasy in task processing logic makes several trailing calls
  423. // with empty content, we ignore these at the calee site.
  424. if (content.empty()) {
  425. return std::vector<json>({json::object()});
  426. }
  427. choices = json::array({json{
  428. {"finish_reason", nullptr},
  429. {"index", 0},
  430. {"delta",
  431. json{
  432. {"content", content},
  433. }},
  434. }});
  435. }
  436. }
  437. json ret = json {
  438. {"choices", choices},
  439. {"created", t},
  440. {"id", oaicompat_cmpl_id},
  441. {"model", oaicompat_model},
  442. {"object", "chat.completion.chunk"}
  443. };
  444. if (timings.prompt_n >= 0) {
  445. ret.push_back({"timings", timings.to_json()});
  446. }
  447. if (!finish_reason.empty()) {
  448. ret.push_back({"usage", json {
  449. {"completion_tokens", n_decoded},
  450. {"prompt_tokens", n_prompt_tokens},
  451. {"total_tokens", n_decoded + n_prompt_tokens},
  452. }});
  453. }
  454. return std::vector<json>({ret});
  455. }
  456. };
  457. struct server_task_result_embd : server_task_result {
  458. int index = 0;
  459. std::vector<float> embedding;
  460. virtual int get_index() override {
  461. return index;
  462. }
  463. virtual json to_json() override {
  464. return json {
  465. {"index", index},
  466. {"embedding", embedding},
  467. };
  468. }
  469. };
  470. struct server_task_result_rerank : server_task_result {
  471. int index = 0;
  472. float score = -1e6;
  473. virtual int get_index() override {
  474. return index;
  475. }
  476. virtual json to_json() override {
  477. return json {
  478. {"index", index},
  479. {"score", score},
  480. };
  481. }
  482. };
  483. // this function maybe used outside of server_task_result_error
  484. static json format_error_response(const std::string & message, const enum error_type type) {
  485. std::string type_str;
  486. int code = 500;
  487. switch (type) {
  488. case ERROR_TYPE_INVALID_REQUEST:
  489. type_str = "invalid_request_error";
  490. code = 400;
  491. break;
  492. case ERROR_TYPE_AUTHENTICATION:
  493. type_str = "authentication_error";
  494. code = 401;
  495. break;
  496. case ERROR_TYPE_NOT_FOUND:
  497. type_str = "not_found_error";
  498. code = 404;
  499. break;
  500. case ERROR_TYPE_SERVER:
  501. type_str = "server_error";
  502. code = 500;
  503. break;
  504. case ERROR_TYPE_PERMISSION:
  505. type_str = "permission_error";
  506. code = 403;
  507. break;
  508. case ERROR_TYPE_NOT_SUPPORTED:
  509. type_str = "not_supported_error";
  510. code = 501;
  511. break;
  512. case ERROR_TYPE_UNAVAILABLE:
  513. type_str = "unavailable_error";
  514. code = 503;
  515. break;
  516. }
  517. return json {
  518. {"code", code},
  519. {"message", message},
  520. {"type", type_str},
  521. };
  522. }
  523. struct server_task_result_error : server_task_result {
  524. int index = 0;
  525. error_type err_type = ERROR_TYPE_SERVER;
  526. std::string err_msg;
  527. virtual bool is_error() override {
  528. return true;
  529. }
  530. virtual json to_json() override {
  531. return format_error_response(err_msg, err_type);
  532. }
  533. };
  534. struct server_task_result_metrics : server_task_result {
  535. int n_idle_slots;
  536. int n_processing_slots;
  537. int n_tasks_deferred;
  538. int64_t t_start;
  539. int32_t kv_cache_tokens_count;
  540. int32_t kv_cache_used_cells;
  541. // TODO: somehow reuse server_metrics in the future, instead of duplicating the fields
  542. uint64_t n_prompt_tokens_processed_total = 0;
  543. uint64_t t_prompt_processing_total = 0;
  544. uint64_t n_tokens_predicted_total = 0;
  545. uint64_t t_tokens_generation_total = 0;
  546. uint64_t n_prompt_tokens_processed = 0;
  547. uint64_t t_prompt_processing = 0;
  548. uint64_t n_tokens_predicted = 0;
  549. uint64_t t_tokens_generation = 0;
  550. uint64_t n_decode_total = 0;
  551. uint64_t n_busy_slots_total = 0;
  552. // TODO: get rid of this json object and use to_json() instead
  553. json slots_data = json::array();
  554. virtual json to_json() override {
  555. return json {
  556. { "idle", n_idle_slots },
  557. { "processing", n_processing_slots },
  558. { "deferred", n_tasks_deferred },
  559. { "t_start", t_start },
  560. { "n_prompt_tokens_processed_total", n_prompt_tokens_processed_total },
  561. { "t_tokens_generation_total", t_tokens_generation_total },
  562. { "n_tokens_predicted_total", n_tokens_predicted_total },
  563. { "t_prompt_processing_total", t_prompt_processing_total },
  564. { "n_prompt_tokens_processed", n_prompt_tokens_processed },
  565. { "t_prompt_processing", t_prompt_processing },
  566. { "n_tokens_predicted", n_tokens_predicted },
  567. { "t_tokens_generation", t_tokens_generation },
  568. { "n_decode_total", n_decode_total },
  569. { "n_busy_slots_total", n_busy_slots_total },
  570. { "kv_cache_tokens_count", kv_cache_tokens_count },
  571. { "kv_cache_used_cells", kv_cache_used_cells },
  572. { "slots", slots_data },
  573. };
  574. }
  575. };
  576. struct server_task_result_slot_save_load : server_task_result {
  577. std::string filename;
  578. bool is_save; // true = save, false = load
  579. size_t n_tokens;
  580. size_t n_bytes;
  581. double t_ms;
  582. virtual json to_json() override {
  583. if (is_save) {
  584. return json {
  585. { "id_slot", id_slot },
  586. { "filename", filename },
  587. { "n_saved", n_tokens },
  588. { "n_written", n_bytes },
  589. { "timings", {
  590. { "save_ms", t_ms }
  591. }},
  592. };
  593. } else {
  594. return json {
  595. { "id_slot", id_slot },
  596. { "filename", filename },
  597. { "n_restored", n_tokens },
  598. { "n_read", n_bytes },
  599. { "timings", {
  600. { "restore_ms", t_ms }
  601. }},
  602. };
  603. }
  604. }
  605. };
  606. struct server_task_result_slot_erase : server_task_result {
  607. size_t n_erased;
  608. virtual json to_json() override {
  609. return json {
  610. { "id_slot", id_slot },
  611. { "n_erased", n_erased },
  612. };
  613. }
  614. };
  615. struct server_task_result_apply_lora : server_task_result {
  616. virtual json to_json() override {
  617. return json {{ "success", true }};
  618. }
  619. };
  620. struct server_slot {
  621. int id;
  622. int id_task = -1;
  623. llama_batch batch_spec = {};
  624. llama_context * ctx_dft = nullptr;
  625. common_speculative * spec = nullptr;
  626. // the index relative to completion multi-task request
  627. size_t index = 0;
  628. struct slot_params params;
  629. slot_state state = SLOT_STATE_IDLE;
  630. // used to determine the slot that has been used the longest
  631. int64_t t_last_used = -1;
  632. // generation props
  633. int32_t n_ctx = 0; // context size per slot
  634. int32_t n_past = 0;
  635. int32_t n_decoded = 0;
  636. int32_t n_remaining = -1;
  637. int32_t i_batch = -1;
  638. int32_t n_predict = -1; // TODO: disambiguate from params.n_predict
  639. // n_prompt_tokens may not be equal to prompt_tokens.size(), because prompt maybe truncated
  640. int32_t n_prompt_tokens = 0;
  641. int32_t n_prompt_tokens_processed = 0;
  642. // input prompt tokens
  643. llama_tokens prompt_tokens;
  644. size_t last_nl_pos = 0;
  645. std::string generated_text;
  646. llama_tokens cache_tokens;
  647. std::vector<completion_token_output> generated_token_probs;
  648. server_task_inf_type inf_type = SERVER_TASK_INF_TYPE_COMPLETION;
  649. bool has_next_token = true;
  650. bool has_new_line = false;
  651. bool truncated = false;
  652. stop_type stop;
  653. std::string stopping_word;
  654. // sampling
  655. json json_schema;
  656. struct common_sampler * smpl = nullptr;
  657. llama_token sampled;
  658. // stats
  659. size_t n_sent_text = 0; // number of sent text character
  660. size_t n_sent_token_probs = 0;
  661. int64_t t_start_process_prompt;
  662. int64_t t_start_generation;
  663. double t_prompt_processing; // ms
  664. double t_token_generation; // ms
  665. std::function<void(int)> callback_on_release;
  666. void reset() {
  667. SLT_DBG(*this, "%s", "\n");
  668. n_prompt_tokens = 0;
  669. last_nl_pos = 0;
  670. generated_text = "";
  671. has_new_line = false;
  672. truncated = false;
  673. stop = STOP_TYPE_NONE;
  674. stopping_word = "";
  675. n_past = 0;
  676. n_sent_text = 0;
  677. n_sent_token_probs = 0;
  678. inf_type = SERVER_TASK_INF_TYPE_COMPLETION;
  679. generated_token_probs.clear();
  680. }
  681. bool has_budget(const common_params & global_params) {
  682. if (params.n_predict == -1 && global_params.n_predict == -1) {
  683. return true; // limitless
  684. }
  685. n_remaining = -1;
  686. if (params.n_predict != -1) {
  687. n_remaining = params.n_predict - n_decoded;
  688. } else if (global_params.n_predict != -1) {
  689. n_remaining = global_params.n_predict - n_decoded;
  690. }
  691. return n_remaining > 0; // no budget
  692. }
  693. bool is_processing() const {
  694. return state != SLOT_STATE_IDLE;
  695. }
  696. bool can_speculate() const {
  697. return ctx_dft && params.speculative.n_max > 0 && params.cache_prompt;
  698. }
  699. void add_token(const completion_token_output & token) {
  700. if (!is_processing()) {
  701. SLT_WRN(*this, "%s", "slot is not processing\n");
  702. return;
  703. }
  704. generated_token_probs.push_back(token);
  705. }
  706. void release() {
  707. if (is_processing()) {
  708. SLT_INF(*this, "stop processing: n_past = %d, truncated = %d\n", n_past, truncated);
  709. t_last_used = ggml_time_us();
  710. t_token_generation = (ggml_time_us() - t_start_generation) / 1e3;
  711. state = SLOT_STATE_IDLE;
  712. callback_on_release(id);
  713. }
  714. }
  715. result_timings get_timings() const {
  716. result_timings timings;
  717. timings.prompt_n = n_prompt_tokens_processed;
  718. timings.prompt_ms = t_prompt_processing;
  719. timings.prompt_per_token_ms = t_prompt_processing / n_prompt_tokens_processed;
  720. timings.prompt_per_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  721. timings.predicted_n = n_decoded;
  722. timings.predicted_ms = t_token_generation;
  723. timings.predicted_per_token_ms = t_token_generation / n_decoded;
  724. timings.predicted_per_second = 1e3 / t_token_generation * n_decoded;
  725. return timings;
  726. }
  727. size_t find_stopping_strings(const std::string & text, const size_t last_token_size, bool is_full_stop) {
  728. size_t stop_pos = std::string::npos;
  729. for (const std::string & word : params.antiprompt) {
  730. size_t pos;
  731. if (is_full_stop) {
  732. const size_t tmp = word.size() + last_token_size;
  733. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  734. pos = text.find(word, from_pos);
  735. } else {
  736. // otherwise, partial stop
  737. pos = find_partial_stop_string(word, text);
  738. }
  739. if (pos != std::string::npos && (stop_pos == std::string::npos || pos < stop_pos)) {
  740. if (is_full_stop) {
  741. stop = STOP_TYPE_WORD;
  742. stopping_word = word;
  743. has_next_token = false;
  744. }
  745. stop_pos = pos;
  746. }
  747. }
  748. return stop_pos;
  749. }
  750. void print_timings() const {
  751. const double t_prompt = t_prompt_processing / n_prompt_tokens_processed;
  752. const double n_prompt_second = 1e3 / t_prompt_processing * n_prompt_tokens_processed;
  753. const double t_gen = t_token_generation / n_decoded;
  754. const double n_gen_second = 1e3 / t_token_generation * n_decoded;
  755. SLT_INF(*this,
  756. "\n"
  757. "\rprompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n"
  758. "\r eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n"
  759. "\r total time = %10.2f ms / %5d tokens\n",
  760. t_prompt_processing, n_prompt_tokens_processed, t_prompt, n_prompt_second,
  761. t_token_generation, n_decoded, t_gen, n_gen_second,
  762. t_prompt_processing + t_token_generation, n_prompt_tokens_processed + n_decoded);
  763. }
  764. };
  765. struct server_metrics {
  766. int64_t t_start = 0;
  767. uint64_t n_prompt_tokens_processed_total = 0;
  768. uint64_t t_prompt_processing_total = 0;
  769. uint64_t n_tokens_predicted_total = 0;
  770. uint64_t t_tokens_generation_total = 0;
  771. uint64_t n_prompt_tokens_processed = 0;
  772. uint64_t t_prompt_processing = 0;
  773. uint64_t n_tokens_predicted = 0;
  774. uint64_t t_tokens_generation = 0;
  775. uint64_t n_decode_total = 0;
  776. uint64_t n_busy_slots_total = 0;
  777. void init() {
  778. t_start = ggml_time_us();
  779. }
  780. void on_prompt_eval(const server_slot & slot) {
  781. n_prompt_tokens_processed_total += slot.n_prompt_tokens_processed;
  782. n_prompt_tokens_processed += slot.n_prompt_tokens_processed;
  783. t_prompt_processing += slot.t_prompt_processing;
  784. t_prompt_processing_total += slot.t_prompt_processing;
  785. }
  786. void on_prediction(const server_slot & slot) {
  787. n_tokens_predicted_total += slot.n_decoded;
  788. n_tokens_predicted += slot.n_decoded;
  789. t_tokens_generation += slot.t_token_generation;
  790. t_tokens_generation_total += slot.t_token_generation;
  791. }
  792. void on_decoded(const std::vector<server_slot> & slots) {
  793. n_decode_total++;
  794. for (const auto & slot : slots) {
  795. if (slot.is_processing()) {
  796. n_busy_slots_total++;
  797. }
  798. }
  799. }
  800. void reset_bucket() {
  801. n_prompt_tokens_processed = 0;
  802. t_prompt_processing = 0;
  803. n_tokens_predicted = 0;
  804. t_tokens_generation = 0;
  805. }
  806. };
  807. struct server_queue {
  808. int id = 0;
  809. bool running;
  810. // queues
  811. std::deque<server_task> queue_tasks;
  812. std::deque<server_task> queue_tasks_deferred;
  813. std::mutex mutex_tasks;
  814. std::condition_variable condition_tasks;
  815. // callback functions
  816. std::function<void(server_task)> callback_new_task;
  817. std::function<void(void)> callback_update_slots;
  818. // Add a new task to the end of the queue
  819. int post(server_task task, bool front = false) {
  820. std::unique_lock<std::mutex> lock(mutex_tasks);
  821. if (task.id == -1) {
  822. task.id = id++;
  823. }
  824. QUE_DBG("new task, id = %d, front = %d\n", task.id, front);
  825. if (front) {
  826. queue_tasks.push_front(std::move(task));
  827. } else {
  828. queue_tasks.push_back(std::move(task));
  829. }
  830. condition_tasks.notify_one();
  831. return task.id;
  832. }
  833. // multi-task version of post()
  834. int post(std::vector<server_task> & tasks, bool front = false) {
  835. std::unique_lock<std::mutex> lock(mutex_tasks);
  836. for (auto & task : tasks) {
  837. if (task.id == -1) {
  838. task.id = id++;
  839. }
  840. QUE_DBG("new task, id = %d/%d, front = %d\n", task.id, (int) tasks.size(), front);
  841. if (front) {
  842. queue_tasks.push_front(std::move(task));
  843. } else {
  844. queue_tasks.push_back(std::move(task));
  845. }
  846. }
  847. condition_tasks.notify_one();
  848. return 0;
  849. }
  850. // Add a new task, but defer until one slot is available
  851. void defer(server_task task) {
  852. std::unique_lock<std::mutex> lock(mutex_tasks);
  853. QUE_DBG("defer task, id = %d\n", task.id);
  854. queue_tasks_deferred.push_back(std::move(task));
  855. condition_tasks.notify_one();
  856. }
  857. // Get the next id for creating a new task
  858. int get_new_id() {
  859. std::unique_lock<std::mutex> lock(mutex_tasks);
  860. int new_id = id++;
  861. return new_id;
  862. }
  863. // Register function to process a new task
  864. void on_new_task(std::function<void(server_task)> callback) {
  865. callback_new_task = std::move(callback);
  866. }
  867. // Register the function to be called when all slots data is ready to be processed
  868. void on_update_slots(std::function<void(void)> callback) {
  869. callback_update_slots = std::move(callback);
  870. }
  871. // Call when the state of one slot is changed, it will move one task from deferred to main queue
  872. void pop_deferred_task() {
  873. std::unique_lock<std::mutex> lock(mutex_tasks);
  874. if (!queue_tasks_deferred.empty()) {
  875. queue_tasks.emplace_back(std::move(queue_tasks_deferred.front()));
  876. queue_tasks_deferred.pop_front();
  877. }
  878. condition_tasks.notify_one();
  879. }
  880. // end the start_loop routine
  881. void terminate() {
  882. std::unique_lock<std::mutex> lock(mutex_tasks);
  883. running = false;
  884. condition_tasks.notify_all();
  885. }
  886. /**
  887. * Main loop consists of these steps:
  888. * - Wait until a new task arrives
  889. * - Process the task (i.e. maybe copy data into slot)
  890. * - Check if multitask is finished
  891. * - Update all slots
  892. */
  893. void start_loop() {
  894. running = true;
  895. while (true) {
  896. QUE_DBG("%s", "processing new tasks\n");
  897. while (true) {
  898. std::unique_lock<std::mutex> lock(mutex_tasks);
  899. if (queue_tasks.empty()) {
  900. lock.unlock();
  901. break;
  902. }
  903. server_task task = queue_tasks.front();
  904. queue_tasks.pop_front();
  905. lock.unlock();
  906. QUE_DBG("processing task, id = %d\n", task.id);
  907. callback_new_task(std::move(task));
  908. }
  909. // all tasks in the current loop is processed, slots data is now ready
  910. QUE_DBG("%s", "update slots\n");
  911. callback_update_slots();
  912. QUE_DBG("%s", "waiting for new tasks\n");
  913. {
  914. std::unique_lock<std::mutex> lock(mutex_tasks);
  915. if (queue_tasks.empty()) {
  916. if (!running) {
  917. QUE_DBG("%s", "terminate\n");
  918. return;
  919. }
  920. condition_tasks.wait(lock, [&]{
  921. return (!queue_tasks.empty() || !running);
  922. });
  923. }
  924. }
  925. }
  926. }
  927. };
  928. struct server_response {
  929. // for keeping track of all tasks waiting for the result
  930. std::unordered_set<int> waiting_task_ids;
  931. // the main result queue (using ptr for polymorphism)
  932. std::vector<server_task_result_ptr> queue_results;
  933. std::mutex mutex_results;
  934. std::condition_variable condition_results;
  935. // add the id_task to the list of tasks waiting for response
  936. void add_waiting_task_id(int id_task) {
  937. SRV_DBG("add task %d to waiting list. current waiting = %d (before add)\n", id_task, (int) waiting_task_ids.size());
  938. std::unique_lock<std::mutex> lock(mutex_results);
  939. waiting_task_ids.insert(id_task);
  940. }
  941. void add_waiting_tasks(const std::vector<server_task> & tasks) {
  942. std::unique_lock<std::mutex> lock(mutex_results);
  943. for (const auto & task : tasks) {
  944. SRV_DBG("add task %d to waiting list. current waiting = %d (before add)\n", task.id, (int) waiting_task_ids.size());
  945. waiting_task_ids.insert(task.id);
  946. }
  947. }
  948. // when the request is finished, we can remove task associated with it
  949. void remove_waiting_task_id(int id_task) {
  950. SRV_DBG("remove task %d from waiting list. current waiting = %d (before remove)\n", id_task, (int) waiting_task_ids.size());
  951. std::unique_lock<std::mutex> lock(mutex_results);
  952. waiting_task_ids.erase(id_task);
  953. }
  954. void remove_waiting_task_ids(const std::unordered_set<int> & id_tasks) {
  955. std::unique_lock<std::mutex> lock(mutex_results);
  956. for (const auto & id_task : id_tasks) {
  957. SRV_DBG("remove task %d from waiting list. current waiting = %d (before remove)\n", id_task, (int) waiting_task_ids.size());
  958. waiting_task_ids.erase(id_task);
  959. }
  960. }
  961. // This function blocks the thread until there is a response for one of the id_tasks
  962. server_task_result_ptr recv(const std::unordered_set<int> & id_tasks) {
  963. while (true) {
  964. std::unique_lock<std::mutex> lock(mutex_results);
  965. condition_results.wait(lock, [&]{
  966. return !queue_results.empty();
  967. });
  968. for (int i = 0; i < (int) queue_results.size(); i++) {
  969. if (id_tasks.find(queue_results[i]->id) != id_tasks.end()) {
  970. server_task_result_ptr res = std::move(queue_results[i]);
  971. queue_results.erase(queue_results.begin() + i);
  972. return res;
  973. }
  974. }
  975. }
  976. // should never reach here
  977. }
  978. // single-task version of recv()
  979. server_task_result_ptr recv(int id_task) {
  980. std::unordered_set<int> id_tasks = {id_task};
  981. return recv(id_tasks);
  982. }
  983. // Send a new result to a waiting id_task
  984. void send(server_task_result_ptr && result) {
  985. SRV_DBG("sending result for task id = %d\n", result->id);
  986. std::unique_lock<std::mutex> lock(mutex_results);
  987. for (const auto & id_task : waiting_task_ids) {
  988. if (result->id == id_task) {
  989. SRV_DBG("task id = %d pushed to result queue\n", result->id);
  990. queue_results.emplace_back(std::move(result));
  991. condition_results.notify_all();
  992. return;
  993. }
  994. }
  995. }
  996. };
  997. struct server_context {
  998. common_params params_base;
  999. llama_model * model = nullptr;
  1000. llama_context * ctx = nullptr;
  1001. std::vector<common_lora_adapter_container> loras;
  1002. llama_model * model_dft = nullptr;
  1003. llama_context_params cparams_dft;
  1004. llama_batch batch = {};
  1005. bool clean_kv_cache = true;
  1006. bool add_bos_token = true;
  1007. bool has_eos_token = false;
  1008. int32_t n_ctx; // total context for all clients / slots
  1009. // slots / clients
  1010. std::vector<server_slot> slots;
  1011. json default_generation_settings_for_props;
  1012. server_queue queue_tasks;
  1013. server_response queue_results;
  1014. server_metrics metrics;
  1015. // Necessary similarity of prompt for slot selection
  1016. float slot_prompt_similarity = 0.0f;
  1017. ~server_context() {
  1018. if (ctx) {
  1019. llama_free(ctx);
  1020. ctx = nullptr;
  1021. }
  1022. if (model) {
  1023. llama_free_model(model);
  1024. model = nullptr;
  1025. }
  1026. if (model_dft) {
  1027. llama_free_model(model_dft);
  1028. model_dft = nullptr;
  1029. }
  1030. // Clear any sampling context
  1031. for (server_slot & slot : slots) {
  1032. common_sampler_free(slot.smpl);
  1033. slot.smpl = nullptr;
  1034. llama_free(slot.ctx_dft);
  1035. slot.ctx_dft = nullptr;
  1036. common_speculative_free(slot.spec);
  1037. slot.spec = nullptr;
  1038. llama_batch_free(slot.batch_spec);
  1039. }
  1040. llama_batch_free(batch);
  1041. }
  1042. bool load_model(const common_params & params) {
  1043. SRV_INF("loading model '%s'\n", params.model.c_str());
  1044. params_base = params;
  1045. common_init_result llama_init = common_init_from_params(params_base);
  1046. model = llama_init.model;
  1047. ctx = llama_init.context;
  1048. loras = llama_init.lora_adapters;
  1049. if (model == nullptr) {
  1050. SRV_ERR("failed to load model, '%s'\n", params_base.model.c_str());
  1051. return false;
  1052. }
  1053. n_ctx = llama_n_ctx(ctx);
  1054. add_bos_token = llama_add_bos_token(model);
  1055. has_eos_token = !llama_add_eos_token(model);
  1056. if (!params_base.speculative.model.empty()) {
  1057. SRV_INF("loading draft model '%s'\n", params_base.speculative.model.c_str());
  1058. auto params_dft = params_base;
  1059. params_dft.devices = params_base.speculative.devices;
  1060. params_dft.model = params_base.speculative.model;
  1061. params_dft.n_ctx = params_base.speculative.n_ctx == 0 ? params_base.n_ctx / params_base.n_parallel : params_base.speculative.n_ctx;
  1062. params_dft.n_gpu_layers = params_base.speculative.n_gpu_layers;
  1063. params_dft.n_parallel = 1;
  1064. common_init_result llama_init_dft = common_init_from_params(params_dft);
  1065. model_dft = llama_init_dft.model;
  1066. if (model_dft == nullptr) {
  1067. SRV_ERR("failed to load draft model, '%s'\n", params_base.speculative.model.c_str());
  1068. return false;
  1069. }
  1070. if (!common_speculative_are_compatible(ctx, llama_init_dft.context)) {
  1071. SRV_ERR("the draft model '%s' is not compatible with the target model '%s'\n", params_base.speculative.model.c_str(), params_base.model.c_str());
  1072. llama_free (llama_init_dft.context);
  1073. llama_free_model(llama_init_dft.model);
  1074. return false;
  1075. }
  1076. const int n_ctx_dft = llama_n_ctx(llama_init_dft.context);
  1077. cparams_dft = common_context_params_to_llama(params_dft);
  1078. cparams_dft.n_batch = n_ctx_dft;
  1079. // force F16 KV cache for the draft model for extra performance
  1080. cparams_dft.type_k = GGML_TYPE_F16;
  1081. cparams_dft.type_v = GGML_TYPE_F16;
  1082. // the context is not needed - we will create one for each slot
  1083. llama_free(llama_init_dft.context);
  1084. }
  1085. return true;
  1086. }
  1087. bool validate_model_chat_template() const {
  1088. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  1089. std::string template_key = "tokenizer.chat_template";
  1090. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  1091. if (res >= 0) {
  1092. llama_chat_message chat[] = {{"user", "test"}};
  1093. std::string tmpl = std::string(model_template.data(), model_template.size());
  1094. int32_t chat_res = llama_chat_apply_template(model, tmpl.c_str(), chat, 1, true, nullptr, 0);
  1095. return chat_res > 0;
  1096. }
  1097. return false;
  1098. }
  1099. void init() {
  1100. const int32_t n_ctx_slot = n_ctx / params_base.n_parallel;
  1101. SRV_INF("initializing slots, n_slots = %d\n", params_base.n_parallel);
  1102. for (int i = 0; i < params_base.n_parallel; i++) {
  1103. server_slot slot;
  1104. slot.id = i;
  1105. slot.n_ctx = n_ctx_slot;
  1106. slot.n_predict = params_base.n_predict;
  1107. if (model_dft) {
  1108. slot.batch_spec = llama_batch_init(params_base.speculative.n_max + 1, 0, 1);
  1109. slot.ctx_dft = llama_new_context_with_model(model_dft, cparams_dft);
  1110. if (slot.ctx_dft == nullptr) {
  1111. SRV_ERR("%s", "failed to create draft context\n");
  1112. return;
  1113. }
  1114. slot.spec = common_speculative_init(slot.ctx_dft);
  1115. if (slot.spec == nullptr) {
  1116. SRV_ERR("%s", "failed to create speculator\n");
  1117. return;
  1118. }
  1119. }
  1120. SLT_INF(slot, "new slot n_ctx_slot = %d\n", slot.n_ctx);
  1121. slot.params.sampling = params_base.sampling;
  1122. slot.callback_on_release = [this](int) {
  1123. queue_tasks.pop_deferred_task();
  1124. };
  1125. slot.reset();
  1126. slots.push_back(slot);
  1127. }
  1128. default_generation_settings_for_props = slots[0].params.to_json();
  1129. default_generation_settings_for_props["seed"] = -1;
  1130. // the update_slots() logic will always submit a maximum of n_batch or n_parallel tokens
  1131. // note that n_batch can be > n_ctx (e.g. for non-causal attention models such as BERT where the KV cache is not used)
  1132. {
  1133. const int32_t n_batch = llama_n_batch(ctx);
  1134. // only a single seq_id per token is needed
  1135. batch = llama_batch_init(std::max(n_batch, params_base.n_parallel), 0, 1);
  1136. }
  1137. metrics.init();
  1138. }
  1139. server_slot * get_slot_by_id(int id) {
  1140. for (server_slot & slot : slots) {
  1141. if (slot.id == id) {
  1142. return &slot;
  1143. }
  1144. }
  1145. return nullptr;
  1146. }
  1147. server_slot * get_available_slot(const server_task & task) {
  1148. server_slot * ret = nullptr;
  1149. // find the slot that has at least n% prompt similarity
  1150. if (ret == nullptr && slot_prompt_similarity != 0.0f) {
  1151. int lcs_len = 0;
  1152. float similarity = 0;
  1153. for (server_slot & slot : slots) {
  1154. // skip the slot if it is not available
  1155. if (slot.is_processing()) {
  1156. continue;
  1157. }
  1158. // skip the slot if it does not contains cached tokens
  1159. if (slot.cache_tokens.empty()) {
  1160. continue;
  1161. }
  1162. // length of the Longest Common Subsequence between the current slot's prompt and the input prompt
  1163. int cur_lcs_len = common_lcs(slot.cache_tokens, task.prompt_tokens);
  1164. // fraction of the common subsequence length compared to the current slot's prompt length
  1165. float cur_similarity = static_cast<float>(cur_lcs_len) / static_cast<int>(slot.cache_tokens.size());
  1166. // select the current slot if the criteria match
  1167. if (cur_lcs_len > lcs_len && cur_similarity > slot_prompt_similarity) {
  1168. lcs_len = cur_lcs_len;
  1169. similarity = cur_similarity;
  1170. ret = &slot;
  1171. }
  1172. }
  1173. if (ret != nullptr) {
  1174. SLT_DBG(*ret, "selected slot by lcs similarity, lcs_len = %d, similarity = %f\n", lcs_len, similarity);
  1175. }
  1176. }
  1177. // find the slot that has been least recently used
  1178. if (ret == nullptr) {
  1179. int64_t t_last = ggml_time_us();
  1180. for (server_slot & slot : slots) {
  1181. // skip the slot if it is not available
  1182. if (slot.is_processing()) {
  1183. continue;
  1184. }
  1185. // select the current slot if the criteria match
  1186. if (slot.t_last_used < t_last) {
  1187. t_last = slot.t_last_used;
  1188. ret = &slot;
  1189. }
  1190. }
  1191. if (ret != nullptr) {
  1192. SLT_DBG(*ret, "selected slot by lru, t_last = %" PRId64 "\n", t_last);
  1193. }
  1194. }
  1195. return ret;
  1196. }
  1197. bool launch_slot_with_task(server_slot & slot, const server_task & task) {
  1198. // Sampling parameter defaults are loaded from the global server context (but individual requests can still override them)
  1199. slot_params defaults;
  1200. defaults.sampling = params_base.sampling;
  1201. defaults.speculative = params_base.speculative;
  1202. const auto & data = task.data;
  1203. if (data.count("__oaicompat") != 0) {
  1204. std::string model_name = params_base.model_alias.empty() ? DEFAULT_OAICOMPAT_MODEL : params_base.model_alias;
  1205. slot.params.oaicompat = true;
  1206. slot.params.oaicompat_chat = json_value(data, "__oaicompat_chat", false);
  1207. slot.params.oaicompat_model = json_value(data, "model", model_name);
  1208. slot.params.oaicompat_cmpl_id = json_value(data, "completion_id", std::string());
  1209. } else {
  1210. slot.params.oaicompat = false;
  1211. }
  1212. // enabling this will output extra debug information in the HTTP responses from the server
  1213. slot.params.verbose = params_base.verbosity > 9;
  1214. slot.params.timings_per_token = json_value(data, "timings_per_token", false);
  1215. slot.params.stream = json_value(data, "stream", false);
  1216. slot.params.cache_prompt = json_value(data, "cache_prompt", true);
  1217. slot.params.n_predict = json_value(data, "n_predict", json_value(data, "max_tokens", defaults.n_predict));
  1218. slot.params.n_indent = json_value(data, "n_indent", defaults.n_indent);
  1219. slot.params.n_keep = json_value(data, "n_keep", defaults.n_keep);
  1220. slot.params.n_discard = json_value(data, "n_discard", defaults.n_discard);
  1221. //slot.params.t_max_prompt_ms = json_value(data, "t_max_prompt_ms", defaults.t_max_prompt_ms); // TODO: implement
  1222. slot.params.t_max_predict_ms = json_value(data, "t_max_predict_ms", defaults.t_max_predict_ms);
  1223. slot.params.sampling.top_k = json_value(data, "top_k", defaults.sampling.top_k);
  1224. slot.params.sampling.top_p = json_value(data, "top_p", defaults.sampling.top_p);
  1225. slot.params.sampling.min_p = json_value(data, "min_p", defaults.sampling.min_p);
  1226. slot.params.sampling.xtc_probability = json_value(data, "xtc_probability", defaults.sampling.xtc_probability);
  1227. slot.params.sampling.xtc_threshold = json_value(data, "xtc_threshold", defaults.sampling.xtc_threshold);
  1228. slot.params.sampling.typ_p = json_value(data, "typical_p", defaults.sampling.typ_p);
  1229. slot.params.sampling.temp = json_value(data, "temperature", defaults.sampling.temp);
  1230. slot.params.sampling.dynatemp_range = json_value(data, "dynatemp_range", defaults.sampling.dynatemp_range);
  1231. slot.params.sampling.dynatemp_exponent = json_value(data, "dynatemp_exponent", defaults.sampling.dynatemp_exponent);
  1232. slot.params.sampling.penalty_last_n = json_value(data, "repeat_last_n", defaults.sampling.penalty_last_n);
  1233. slot.params.sampling.penalty_repeat = json_value(data, "repeat_penalty", defaults.sampling.penalty_repeat);
  1234. slot.params.sampling.penalty_freq = json_value(data, "frequency_penalty", defaults.sampling.penalty_freq);
  1235. slot.params.sampling.penalty_present = json_value(data, "presence_penalty", defaults.sampling.penalty_present);
  1236. slot.params.sampling.dry_multiplier = json_value(data, "dry_multiplier", defaults.sampling.dry_multiplier);
  1237. slot.params.sampling.dry_base = json_value(data, "dry_base", defaults.sampling.dry_base);
  1238. slot.params.sampling.dry_allowed_length = json_value(data, "dry_allowed_length", defaults.sampling.dry_allowed_length);
  1239. slot.params.sampling.dry_penalty_last_n = json_value(data, "dry_penalty_last_n", defaults.sampling.dry_penalty_last_n);
  1240. slot.params.sampling.mirostat = json_value(data, "mirostat", defaults.sampling.mirostat);
  1241. slot.params.sampling.mirostat_tau = json_value(data, "mirostat_tau", defaults.sampling.mirostat_tau);
  1242. slot.params.sampling.mirostat_eta = json_value(data, "mirostat_eta", defaults.sampling.mirostat_eta);
  1243. slot.params.sampling.penalize_nl = json_value(data, "penalize_nl", defaults.sampling.penalize_nl);
  1244. slot.params.sampling.seed = json_value(data, "seed", defaults.sampling.seed);
  1245. slot.params.sampling.n_probs = json_value(data, "n_probs", defaults.sampling.n_probs);
  1246. slot.params.sampling.min_keep = json_value(data, "min_keep", defaults.sampling.min_keep);
  1247. slot.params.speculative.n_min = json_value(data, "speculative.n_min", defaults.speculative.n_min);
  1248. slot.params.speculative.n_max = json_value(data, "speculative.n_max", defaults.speculative.n_max);
  1249. slot.params.speculative.p_min = json_value(data, "speculative.p_min", defaults.speculative.p_min);
  1250. slot.params.speculative.n_min = std::min(slot.params.speculative.n_max, slot.params.speculative.n_min);
  1251. slot.params.speculative.n_min = std::max(slot.params.speculative.n_min, 2);
  1252. slot.params.speculative.n_max = std::max(slot.params.speculative.n_max, 0);
  1253. if (slot.params.sampling.dry_base < 1.0f) {
  1254. slot.params.sampling.dry_base = defaults.sampling.dry_base;
  1255. }
  1256. // sequence breakers for DRY
  1257. {
  1258. // Currently, this is not compatible with TextGen WebUI, Koboldcpp and SillyTavern format
  1259. // Ref: https://github.com/oobabooga/text-generation-webui/blob/d1af7a41ade7bd3c3a463bfa640725edb818ebaf/extensions/openai/typing.py#L39
  1260. if (data.contains("dry_sequence_breakers")) {
  1261. slot.params.sampling.dry_sequence_breakers = json_value(data, "dry_sequence_breakers", std::vector<std::string>());
  1262. if (slot.params.sampling.dry_sequence_breakers.empty()) {
  1263. send_error(task, "Error: dry_sequence_breakers must be a non-empty array of strings", ERROR_TYPE_INVALID_REQUEST);
  1264. return false;
  1265. }
  1266. }
  1267. }
  1268. // process "json_schema" and "grammar"
  1269. if (data.contains("json_schema") && !data.at("json_schema").is_null() && data.contains("grammar") && !data.at("grammar").is_null()) {
  1270. send_error(task, "Either \"json_schema\" or \"grammar\" can be specified, but not both", ERROR_TYPE_INVALID_REQUEST);
  1271. return false;
  1272. }
  1273. if (data.contains("json_schema") && !data.contains("grammar")) {
  1274. try {
  1275. auto schema = json_value(data, "json_schema", json::object());
  1276. slot.params.sampling.grammar = json_schema_to_grammar(schema);
  1277. } catch (const std::exception & e) {
  1278. send_error(task, std::string("\"json_schema\": ") + e.what(), ERROR_TYPE_INVALID_REQUEST);
  1279. return false;
  1280. }
  1281. } else {
  1282. slot.params.sampling.grammar = json_value(data, "grammar", defaults.sampling.grammar);
  1283. }
  1284. if (slot.n_predict > 0 && slot.params.n_predict > slot.n_predict) {
  1285. // Might be better to reject the request with a 400 ?
  1286. slot.params.n_predict = slot.n_predict;
  1287. SLT_WRN(slot, "n_predict = %d exceeds server configuration, setting to %d", slot.n_predict, slot.n_predict);
  1288. }
  1289. {
  1290. slot.params.sampling.logit_bias.clear();
  1291. if (json_value(data, "ignore_eos", false) && has_eos_token) {
  1292. slot.params.sampling.logit_bias.push_back({llama_token_eos(model), -INFINITY});
  1293. }
  1294. const auto & logit_bias = data.find("logit_bias");
  1295. if (logit_bias != data.end() && logit_bias->is_array()) {
  1296. const int n_vocab = llama_n_vocab(model);
  1297. for (const auto & el : *logit_bias) {
  1298. // TODO: we may want to throw errors here, in case "el" is incorrect
  1299. if (el.is_array() && el.size() == 2) {
  1300. float bias;
  1301. if (el[1].is_number()) {
  1302. bias = el[1].get<float>();
  1303. } else if (el[1].is_boolean() && !el[1].get<bool>()) {
  1304. bias = -INFINITY;
  1305. } else {
  1306. continue;
  1307. }
  1308. if (el[0].is_number_integer()) {
  1309. llama_token tok = el[0].get<llama_token>();
  1310. if (tok >= 0 && tok < n_vocab) {
  1311. slot.params.sampling.logit_bias.push_back({tok, bias});
  1312. }
  1313. } else if (el[0].is_string()) {
  1314. auto toks = common_tokenize(model, el[0].get<std::string>(), false);
  1315. for (auto tok : toks) {
  1316. slot.params.sampling.logit_bias.push_back({tok, bias});
  1317. }
  1318. }
  1319. }
  1320. }
  1321. }
  1322. }
  1323. {
  1324. slot.params.antiprompt.clear();
  1325. const auto & stop = data.find("stop");
  1326. if (stop != data.end() && stop->is_array()) {
  1327. for (const auto & word : *stop) {
  1328. if (!word.empty()) {
  1329. slot.params.antiprompt.push_back(word);
  1330. }
  1331. }
  1332. }
  1333. }
  1334. {
  1335. const auto & samplers = data.find("samplers");
  1336. if (samplers != data.end()) {
  1337. if (samplers->is_array()) {
  1338. std::vector<std::string> sampler_names;
  1339. for (const auto & name : *samplers) {
  1340. if (name.is_string()) {
  1341. sampler_names.emplace_back(name);
  1342. }
  1343. }
  1344. slot.params.sampling.samplers = common_sampler_types_from_names(sampler_names, false);
  1345. } else if (samplers->is_string()){
  1346. std::string sampler_string;
  1347. for (const auto & name : *samplers) {
  1348. sampler_string += name;
  1349. }
  1350. slot.params.sampling.samplers = common_sampler_types_from_chars(sampler_string);
  1351. }
  1352. } else {
  1353. slot.params.sampling.samplers = defaults.sampling.samplers;
  1354. }
  1355. }
  1356. {
  1357. if (slot.smpl != nullptr) {
  1358. common_sampler_free(slot.smpl);
  1359. }
  1360. slot.smpl = common_sampler_init(model, slot.params.sampling);
  1361. if (slot.smpl == nullptr) {
  1362. // for now, the only error that may happen here is invalid grammar
  1363. send_error(task, "Failed to parse grammar", ERROR_TYPE_INVALID_REQUEST);
  1364. return false;
  1365. }
  1366. }
  1367. if (slot.ctx_dft) {
  1368. llama_batch_free(slot.batch_spec);
  1369. slot.batch_spec = llama_batch_init(slot.params.speculative.n_max + 1, 0, 1);
  1370. }
  1371. slot.state = SLOT_STATE_STARTED;
  1372. SLT_INF(slot, "%s", "processing task\n");
  1373. return true;
  1374. }
  1375. void kv_cache_clear() {
  1376. SRV_DBG("%s", "clearing KV cache\n");
  1377. // clear the entire KV cache
  1378. llama_kv_cache_clear(ctx);
  1379. clean_kv_cache = false;
  1380. }
  1381. bool process_token(completion_token_output & result, server_slot & slot) {
  1382. // remember which tokens were sampled - used for repetition penalties during sampling
  1383. const std::string token_str = common_token_to_piece(ctx, result.tok, params_base.special);
  1384. slot.sampled = result.tok;
  1385. // search stop word and delete it
  1386. slot.generated_text += token_str;
  1387. slot.has_next_token = true;
  1388. // check if there is incomplete UTF-8 character at the end
  1389. bool incomplete = false;
  1390. for (unsigned i = 1; i < 5 && i <= slot.generated_text.size(); ++i) {
  1391. unsigned char c = slot.generated_text[slot.generated_text.size() - i];
  1392. if ((c & 0xC0) == 0x80) {
  1393. // continuation byte: 10xxxxxx
  1394. continue;
  1395. }
  1396. if ((c & 0xE0) == 0xC0) {
  1397. // 2-byte character: 110xxxxx ...
  1398. incomplete = i < 2;
  1399. } else if ((c & 0xF0) == 0xE0) {
  1400. // 3-byte character: 1110xxxx ...
  1401. incomplete = i < 3;
  1402. } else if ((c & 0xF8) == 0xF0) {
  1403. // 4-byte character: 11110xxx ...
  1404. incomplete = i < 4;
  1405. }
  1406. // else 1-byte character or invalid byte
  1407. break;
  1408. }
  1409. if (!incomplete) {
  1410. size_t pos = std::min(slot.n_sent_text, slot.generated_text.size());
  1411. const std::string str_test = slot.generated_text.substr(pos);
  1412. bool send_text = true;
  1413. size_t stop_pos = slot.find_stopping_strings(str_test, token_str.size(), true);
  1414. if (stop_pos != std::string::npos) {
  1415. slot.generated_text.erase(
  1416. slot.generated_text.begin() + pos + stop_pos,
  1417. slot.generated_text.end());
  1418. pos = std::min(slot.n_sent_text, slot.generated_text.size());
  1419. } else if (slot.has_next_token) {
  1420. stop_pos = slot.find_stopping_strings(str_test, token_str.size(), false);
  1421. send_text = stop_pos == std::string::npos;
  1422. }
  1423. // check if there is any token to predict
  1424. if (send_text) {
  1425. // no send the stop word in the response
  1426. result.text_to_send = slot.generated_text.substr(pos, std::string::npos);
  1427. slot.n_sent_text += result.text_to_send.size();
  1428. // add the token to slot queue and cache
  1429. }
  1430. slot.add_token(result);
  1431. if (slot.params.stream) {
  1432. send_partial_response(slot, result);
  1433. }
  1434. }
  1435. if (incomplete) {
  1436. slot.has_next_token = true;
  1437. }
  1438. // check the limits
  1439. if (slot.n_decoded > 0 && slot.has_next_token && !slot.has_budget(params_base)) {
  1440. slot.stop = STOP_TYPE_LIMIT;
  1441. slot.has_next_token = false;
  1442. SLT_DBG(slot, "stopped by limit, n_decoded = %d, n_predict = %d\n", slot.n_decoded, slot.params.n_predict);
  1443. }
  1444. if (slot.has_new_line) {
  1445. // if we have already seen a new line, we stop after a certain time limit
  1446. if (slot.params.t_max_predict_ms > 0 && (ggml_time_us() - slot.t_start_generation > 1000.0f*slot.params.t_max_predict_ms)) {
  1447. slot.stop = STOP_TYPE_LIMIT;
  1448. slot.has_next_token = false;
  1449. SLT_DBG(slot, "stopped by time limit, n_decoded = %d, t_max_predict_ms = %d ms\n", slot.n_decoded, (int) slot.params.t_max_predict_ms);
  1450. }
  1451. // require that each new line has a whitespace prefix (i.e. indentation) of at least slot.params.n_indent
  1452. if (slot.params.n_indent > 0) {
  1453. // check the current indentation
  1454. // TODO: improve by not doing it more than once for each new line
  1455. if (slot.last_nl_pos > 0) {
  1456. size_t pos = slot.last_nl_pos;
  1457. int n_indent = 0;
  1458. while (pos < slot.generated_text.size() && (slot.generated_text[pos] == ' ' || slot.generated_text[pos] == '\t')) {
  1459. n_indent++;
  1460. pos++;
  1461. }
  1462. if (pos < slot.generated_text.size() && n_indent < slot.params.n_indent) {
  1463. slot.stop = STOP_TYPE_LIMIT;
  1464. slot.has_next_token = false;
  1465. // cut the last line
  1466. slot.generated_text.erase(pos, std::string::npos);
  1467. SLT_DBG(slot, "stopped by indentation limit, n_decoded = %d, n_indent = %d\n", slot.n_decoded, n_indent);
  1468. }
  1469. }
  1470. // find the next new line
  1471. {
  1472. const size_t pos = slot.generated_text.find('\n', slot.last_nl_pos);
  1473. if (pos != std::string::npos) {
  1474. slot.last_nl_pos = pos + 1;
  1475. }
  1476. }
  1477. }
  1478. }
  1479. // check if there is a new line in the generated text
  1480. if (result.text_to_send.find('\n') != std::string::npos) {
  1481. slot.has_new_line = true;
  1482. }
  1483. // if context shift is disabled, we stop when it reaches the context limit
  1484. if (slot.n_past >= slot.n_ctx) {
  1485. slot.truncated = true;
  1486. slot.stop = STOP_TYPE_LIMIT;
  1487. slot.has_next_token = false;
  1488. SLT_DBG(slot, "stopped due to running out of context capacity, n_past = %d, n_prompt_tokens = %d, n_decoded = %d, n_ctx = %d\n",
  1489. slot.n_decoded, slot.n_prompt_tokens, slot.n_past, slot.n_ctx);
  1490. }
  1491. if (llama_token_is_eog(model, result.tok)) {
  1492. slot.stop = STOP_TYPE_EOS;
  1493. slot.has_next_token = false;
  1494. SLT_DBG(slot, "%s", "stopped by EOS\n");
  1495. }
  1496. const auto n_ctx_train = llama_n_ctx_train(model);
  1497. if (slot.params.n_predict < 1 && slot.n_predict < 1 && slot.n_prompt_tokens + slot.n_decoded >= n_ctx_train) {
  1498. slot.truncated = true;
  1499. slot.stop = STOP_TYPE_LIMIT;
  1500. slot.has_next_token = false; // stop prediction
  1501. SLT_WRN(slot,
  1502. "n_predict (%d) is set for infinite generation. "
  1503. "Limiting generated tokens to n_ctx_train (%d) to avoid EOS-less generation infinite loop\n",
  1504. slot.params.n_predict, n_ctx_train);
  1505. }
  1506. SLT_DBG(slot, "n_decoded = %d, n_remaining = %d, next token: %5d '%s'\n", slot.n_decoded, slot.n_remaining, result.tok, token_str.c_str());
  1507. return slot.has_next_token; // continue
  1508. }
  1509. void send_error(const server_task & task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1510. send_error(task.id, error, type);
  1511. }
  1512. void send_error(const server_slot & slot, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1513. send_error(slot.id_task, error, type);
  1514. }
  1515. void send_error(const int id_task, const std::string & error, const enum error_type type = ERROR_TYPE_SERVER) {
  1516. SRV_ERR("task id = %d, error: %s\n", id_task, error.c_str());
  1517. auto res = std::make_unique<server_task_result_error>();
  1518. res->id = id_task;
  1519. res->err_type = type;
  1520. res->err_msg = error;
  1521. queue_results.send(std::move(res));
  1522. }
  1523. void send_partial_response(server_slot & slot, completion_token_output tkn) {
  1524. auto res = std::make_unique<server_task_result_cmpl_partial>();
  1525. res->id = slot.id_task;
  1526. res->index = slot.index;
  1527. res->content = tkn.text_to_send;
  1528. res->truncated = slot.truncated;
  1529. res->n_decoded = slot.n_decoded;
  1530. res->n_prompt_tokens = slot.n_prompt_tokens;
  1531. res->stop = slot.stop;
  1532. res->verbose = slot.params.verbose;
  1533. res->oaicompat = slot.params.oaicompat;
  1534. res->oaicompat_chat = slot.params.oaicompat_chat;
  1535. res->oaicompat_model = slot.params.oaicompat_model;
  1536. res->oaicompat_cmpl_id = slot.params.oaicompat_cmpl_id;
  1537. // populate res.probs_output
  1538. if (slot.params.sampling.n_probs > 0) {
  1539. const llama_tokens to_send_toks = common_tokenize(ctx, tkn.text_to_send, false);
  1540. const size_t probs_pos = std::min(slot.n_sent_token_probs, slot.generated_token_probs.size());
  1541. const size_t probs_stop_pos = std::min(slot.n_sent_token_probs + to_send_toks.size(), slot.generated_token_probs.size());
  1542. std::vector<completion_token_output> probs_output;
  1543. if (probs_pos < probs_stop_pos) {
  1544. res->probs_output = std::vector<completion_token_output>(
  1545. slot.generated_token_probs.begin() + probs_pos,
  1546. slot.generated_token_probs.begin() + probs_stop_pos);
  1547. }
  1548. }
  1549. // populate timings if this is final response or timings_per_token is enabled
  1550. if (slot.stop != STOP_TYPE_NONE || slot.params.timings_per_token) {
  1551. res->timings = slot.get_timings();
  1552. }
  1553. queue_results.send(std::move(res));
  1554. }
  1555. void send_final_response(server_slot & slot) {
  1556. if (slot.params.stream) {
  1557. // if in stream mode, send the last partial response
  1558. return send_partial_response(slot, {0, "", {}});
  1559. }
  1560. auto res = std::make_unique<server_task_result_cmpl_final>();
  1561. res->id = slot.id_task;
  1562. res->id_slot = slot.id;
  1563. res->index = slot.index;
  1564. res->content = slot.generated_text;
  1565. res->timings = slot.get_timings();
  1566. res->prompt = common_detokenize(ctx, slot.prompt_tokens, true);
  1567. res->truncated = slot.truncated;
  1568. res->n_decoded = slot.n_decoded;
  1569. res->n_prompt_tokens = slot.n_prompt_tokens;
  1570. res->n_tokens_cached = slot.n_past;
  1571. res->has_new_line = slot.has_new_line;
  1572. res->stopping_word = slot.stopping_word;
  1573. res->stop = slot.stop;
  1574. res->verbose = slot.params.verbose;
  1575. res->oaicompat = slot.params.oaicompat;
  1576. res->oaicompat_chat = slot.params.oaicompat_chat;
  1577. res->oaicompat_model = slot.params.oaicompat_model;
  1578. res->oaicompat_cmpl_id = slot.params.oaicompat_cmpl_id;
  1579. // populate res.probs_output
  1580. if (slot.params.sampling.n_probs > 0) {
  1581. if (!slot.params.stream && slot.stop == STOP_TYPE_WORD) {
  1582. const llama_tokens stop_word_toks = common_tokenize(ctx, slot.stopping_word, false);
  1583. size_t safe_offset = std::min(slot.generated_token_probs.size(), stop_word_toks.size());
  1584. res->probs_output = std::vector<completion_token_output>(
  1585. slot.generated_token_probs.begin(),
  1586. slot.generated_token_probs.end() - safe_offset);
  1587. } else {
  1588. res->probs_output = std::vector<completion_token_output>(
  1589. slot.generated_token_probs.begin(),
  1590. slot.generated_token_probs.end());
  1591. }
  1592. }
  1593. res->generation_params = slot.params; // copy the parameters
  1594. queue_results.send(std::move(res));
  1595. }
  1596. void send_embedding(const server_slot & slot, const llama_batch & batch) {
  1597. auto res = std::make_unique<server_task_result_embd>();
  1598. res->id = slot.id_task;
  1599. res->index = slot.index;
  1600. const int n_embd = llama_n_embd(model);
  1601. std::vector<float> embd_res(n_embd, 0.0f);
  1602. for (int i = 0; i < batch.n_tokens; ++i) {
  1603. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  1604. continue;
  1605. }
  1606. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1607. if (embd == NULL) {
  1608. embd = llama_get_embeddings_ith(ctx, i);
  1609. }
  1610. if (embd == NULL) {
  1611. SLT_ERR(slot, "failed to get embeddings, token = %d, seq_id = %d\n", batch.token[i], batch.seq_id[i][0]);
  1612. res->embedding = std::vector<float>(n_embd, 0.0f);
  1613. continue;
  1614. }
  1615. common_embd_normalize(embd, embd_res.data(), n_embd);
  1616. res->embedding = embd_res;
  1617. }
  1618. SLT_DBG(slot, "%s", "sending embeddings\n");
  1619. queue_results.send(std::move(res));
  1620. }
  1621. void send_rerank(const server_slot & slot, const llama_batch & batch) {
  1622. auto res = std::make_unique<server_task_result_rerank>();
  1623. res->id = slot.id_task;
  1624. res->index = slot.index;
  1625. for (int i = 0; i < batch.n_tokens; ++i) {
  1626. if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
  1627. continue;
  1628. }
  1629. const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
  1630. if (embd == NULL) {
  1631. embd = llama_get_embeddings_ith(ctx, i);
  1632. }
  1633. if (embd == NULL) {
  1634. SLT_ERR(slot, "failed to get embeddings, token = %d, seq_id = %d\n", batch.token[i], batch.seq_id[i][0]);
  1635. res->score = -1e6;
  1636. continue;
  1637. }
  1638. res->score = embd[0];
  1639. }
  1640. SLT_DBG(slot, "sending rerank result, res.score = %f\n", res->score);
  1641. queue_results.send(std::move(res));
  1642. }
  1643. //
  1644. // Functions to create new task(s) and receive result(s)
  1645. //
  1646. // break the input "prompt" into multiple tasks if needed, then format and tokenize the input prompt(s)
  1647. std::vector<server_task> create_tasks_inference(json data, server_task_inf_type inf_type) {
  1648. std::vector<server_task> tasks;
  1649. auto create_task = [&](json & task_data, llama_tokens & prompt_tokens) {
  1650. SRV_DBG("create task, n_tokens = %d\n", (int) prompt_tokens.size());
  1651. server_task task;
  1652. task.id = queue_tasks.get_new_id();
  1653. task.inf_type = inf_type;
  1654. task.type = SERVER_TASK_TYPE_INFERENCE;
  1655. task.data = task_data;
  1656. task.prompt_tokens = std::move(prompt_tokens);
  1657. tasks.push_back(std::move(task));
  1658. };
  1659. static constexpr const char * error_msg = "\"prompt\" must be a string, an array of token ids or an array of prompts";
  1660. if (!data.contains("prompt")) {
  1661. throw std::runtime_error(error_msg);
  1662. }
  1663. // because llama_tokenize api is thread-safe, we can tokenize the prompt from HTTP thread
  1664. bool add_special = inf_type != SERVER_TASK_INF_TYPE_RERANK && inf_type != SERVER_TASK_INF_TYPE_INFILL;
  1665. std::vector<llama_tokens> tokenized_prompts = tokenize_input_prompts(ctx, data.at("prompt"), add_special, true);
  1666. switch (inf_type) {
  1667. case SERVER_TASK_INF_TYPE_RERANK:
  1668. {
  1669. // prompts[0] is the question
  1670. // the rest are the answers/documents
  1671. GGML_ASSERT(tokenized_prompts.size() > 1);
  1672. SRV_DBG("creating rerank tasks, n_prompts = %d\n", (int) tokenized_prompts.size() - 1);
  1673. for (size_t i = 1; i < tokenized_prompts.size(); i++) {
  1674. data["index"] = i - 1;
  1675. auto tokens = format_rerank(model, tokenized_prompts[0], tokenized_prompts[i]);
  1676. create_task(data, tokens);
  1677. }
  1678. } break;
  1679. case SERVER_TASK_INF_TYPE_INFILL:
  1680. {
  1681. SRV_DBG("creating infill tasks, n_prompts = %d\n", (int) tokenized_prompts.size());
  1682. for (size_t i = 0; i < tokenized_prompts.size(); i++) {
  1683. data["index"] = i;
  1684. auto tokens = format_infill(
  1685. ctx,
  1686. data.at("input_prefix"),
  1687. data.at("input_suffix"),
  1688. data.at("input_extra"),
  1689. params_base.n_batch,
  1690. params_base.n_predict,
  1691. slots[0].n_ctx, // TODO: there should be a better way
  1692. params_base.spm_infill,
  1693. tokenized_prompts[i]
  1694. );
  1695. create_task(data, tokens);
  1696. }
  1697. } break;
  1698. default:
  1699. {
  1700. SRV_DBG("creating multi-prompt tasks, n_prompts = %d\n", (int) tokenized_prompts.size());
  1701. for (size_t i = 0; i < tokenized_prompts.size(); i++) {
  1702. data["index"] = i;
  1703. create_task(data, tokenized_prompts[i]);
  1704. }
  1705. }
  1706. }
  1707. return tasks;
  1708. }
  1709. void cancel_tasks(const std::unordered_set<int> & id_tasks) {
  1710. std::vector<server_task> cancel_tasks;
  1711. cancel_tasks.reserve(id_tasks.size());
  1712. for (const auto & id_task : id_tasks) {
  1713. SRV_WRN("cancel task, id_task = %d\n", id_task);
  1714. server_task task;
  1715. task.type = SERVER_TASK_TYPE_CANCEL;
  1716. task.id_target = id_task;
  1717. cancel_tasks.push_back(task);
  1718. queue_results.remove_waiting_task_id(id_task);
  1719. }
  1720. // push to beginning of the queue, so it has highest priority
  1721. queue_tasks.post(cancel_tasks, true);
  1722. }
  1723. // receive the results from task(s) created by create_tasks_inference
  1724. void receive_multi_results(
  1725. const std::unordered_set<int> & id_tasks,
  1726. const std::function<void(std::vector<server_task_result_ptr>&)> & result_handler,
  1727. const std::function<void(json)> & error_handler) {
  1728. std::vector<server_task_result_ptr> results(id_tasks.size());
  1729. for (size_t i = 0; i < id_tasks.size(); i++) {
  1730. server_task_result_ptr result = queue_results.recv(id_tasks);
  1731. if (result->is_error()) {
  1732. error_handler(result->to_json());
  1733. cancel_tasks(id_tasks);
  1734. return;
  1735. }
  1736. GGML_ASSERT(
  1737. dynamic_cast<server_task_result_cmpl_final*>(result.get()) != nullptr
  1738. || dynamic_cast<server_task_result_embd*>(result.get()) != nullptr
  1739. || dynamic_cast<server_task_result_rerank*>(result.get()) != nullptr
  1740. );
  1741. const size_t idx = result->get_index();
  1742. GGML_ASSERT(idx < results.size() && "index out of range");
  1743. results[idx] = std::move(result);
  1744. }
  1745. result_handler(results);
  1746. }
  1747. // receive the results from task(s) created by create_tasks_inference, in stream mode
  1748. void receive_cmpl_results_stream(
  1749. const std::unordered_set<int> & id_tasks,
  1750. const std::function<bool(server_task_result_ptr&)> & result_handler,
  1751. const std::function<void(json)> & error_handler) {
  1752. size_t n_finished = 0;
  1753. while (true) {
  1754. server_task_result_ptr result = queue_results.recv(id_tasks);
  1755. if (result->is_error()) {
  1756. error_handler(result->to_json());
  1757. cancel_tasks(id_tasks);
  1758. return;
  1759. }
  1760. GGML_ASSERT(dynamic_cast<server_task_result_cmpl_partial*>(result.get()) != nullptr);
  1761. if (!result_handler(result)) {
  1762. cancel_tasks(id_tasks);
  1763. break;
  1764. }
  1765. if (result->is_stop()) {
  1766. if (++n_finished == id_tasks.size()) {
  1767. break;
  1768. }
  1769. }
  1770. }
  1771. }
  1772. //
  1773. // Functions to process the task
  1774. //
  1775. void process_single_task(server_task task) {
  1776. switch (task.type) {
  1777. case SERVER_TASK_TYPE_INFERENCE:
  1778. {
  1779. const int id_slot = json_value(task.data, "id_slot", -1);
  1780. server_slot * slot = id_slot != -1 ? get_slot_by_id(id_slot) : get_available_slot(task);
  1781. if (slot == nullptr) {
  1782. // if no slot is available, we defer this task for processing later
  1783. SRV_DBG("no slot is available, defer task, id_task = %d\n", task.id);
  1784. queue_tasks.defer(task);
  1785. break;
  1786. }
  1787. if (slot->is_processing()) {
  1788. // if requested slot is unavailable, we defer this task for processing later
  1789. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1790. queue_tasks.defer(task);
  1791. break;
  1792. }
  1793. slot->reset();
  1794. slot->id_task = task.id;
  1795. slot->inf_type = task.inf_type;
  1796. slot->index = json_value(task.data, "index", 0);
  1797. slot->prompt_tokens = std::move(task.prompt_tokens);
  1798. if (!launch_slot_with_task(*slot, task)) {
  1799. SRV_ERR("failed to launch slot with task, id_task = %d\n", task.id);
  1800. break;
  1801. }
  1802. } break;
  1803. case SERVER_TASK_TYPE_CANCEL:
  1804. {
  1805. // release slot linked with the task id
  1806. for (auto & slot : slots) {
  1807. if (slot.id_task == task.id_target) {
  1808. slot.release();
  1809. break;
  1810. }
  1811. }
  1812. } break;
  1813. case SERVER_TASK_TYPE_NEXT_RESPONSE:
  1814. {
  1815. // do nothing
  1816. } break;
  1817. case SERVER_TASK_TYPE_METRICS:
  1818. {
  1819. json slots_data = json::array();
  1820. int n_idle_slots = 0;
  1821. int n_processing_slots = 0;
  1822. for (server_slot & slot : slots) {
  1823. json slot_data = slot.params.to_json();
  1824. slot_data["id"] = slot.id;
  1825. slot_data["id_task"] = slot.id_task;
  1826. slot_data["is_processing"] = slot.is_processing();
  1827. slot_data["prompt"] = common_detokenize(ctx, slot.prompt_tokens);
  1828. slot_data["next_token"] = {
  1829. {"has_next_token", slot.has_next_token},
  1830. {"has_new_line", slot.has_new_line},
  1831. {"n_remain", slot.n_remaining},
  1832. {"n_decoded", slot.n_decoded},
  1833. {"stopping_word", slot.stopping_word},
  1834. };
  1835. if (slot.is_processing()) {
  1836. n_processing_slots++;
  1837. } else {
  1838. n_idle_slots++;
  1839. }
  1840. slots_data.push_back(slot_data);
  1841. }
  1842. SRV_DBG("n_idle_slots = %d, n_processing_slots = %d\n", n_idle_slots, n_processing_slots);
  1843. auto res = std::make_unique<server_task_result_metrics>();
  1844. res->id = task.id;
  1845. res->n_idle_slots = n_idle_slots;
  1846. res->n_processing_slots = n_processing_slots;
  1847. res->n_tasks_deferred = queue_tasks.queue_tasks_deferred.size();
  1848. res->t_start = metrics.t_start;
  1849. res->kv_cache_tokens_count = llama_get_kv_cache_token_count(ctx);
  1850. res->kv_cache_used_cells = llama_get_kv_cache_used_cells(ctx);
  1851. res->n_prompt_tokens_processed_total = metrics.n_prompt_tokens_processed_total;
  1852. res->t_prompt_processing_total = metrics.t_prompt_processing_total;
  1853. res->n_tokens_predicted_total = metrics.n_tokens_predicted_total;
  1854. res->t_tokens_generation_total = metrics.t_tokens_generation_total;
  1855. res->n_prompt_tokens_processed = metrics.n_prompt_tokens_processed;
  1856. res->t_prompt_processing = metrics.t_prompt_processing;
  1857. res->n_tokens_predicted = metrics.n_tokens_predicted;
  1858. res->t_tokens_generation = metrics.t_tokens_generation;
  1859. res->n_decode_total = metrics.n_decode_total;
  1860. res->n_busy_slots_total = metrics.n_busy_slots_total;
  1861. if (json_value(task.data, "reset_bucket", false)) {
  1862. metrics.reset_bucket();
  1863. }
  1864. queue_results.send(std::move(res));
  1865. } break;
  1866. case SERVER_TASK_TYPE_SLOT_SAVE:
  1867. {
  1868. int id_slot = task.data.at("id_slot");
  1869. server_slot * slot = get_slot_by_id(id_slot);
  1870. if (slot == nullptr) {
  1871. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1872. break;
  1873. }
  1874. if (slot->is_processing()) {
  1875. // if requested slot is unavailable, we defer this task for processing later
  1876. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1877. queue_tasks.defer(task);
  1878. break;
  1879. }
  1880. const size_t token_count = slot->cache_tokens.size();
  1881. const int64_t t_start = ggml_time_us();
  1882. std::string filename = task.data.at("filename");
  1883. std::string filepath = task.data.at("filepath");
  1884. const size_t nwrite = llama_state_seq_save_file(ctx, filepath.c_str(), slot->id, slot->cache_tokens.data(), token_count);
  1885. const int64_t t_end = ggml_time_us();
  1886. const double t_save_ms = (t_end - t_start) / 1000.0;
  1887. auto res = std::make_unique<server_task_result_slot_save_load>();
  1888. res->id = task.id;
  1889. res->id_slot = id_slot;
  1890. res->filename = filename;
  1891. res->is_save = true;
  1892. res->n_tokens = token_count;
  1893. res->n_bytes = nwrite;
  1894. res->t_ms = t_save_ms;
  1895. queue_results.send(std::move(res));
  1896. } break;
  1897. case SERVER_TASK_TYPE_SLOT_RESTORE:
  1898. {
  1899. int id_slot = task.data.at("id_slot");
  1900. server_slot * slot = get_slot_by_id(id_slot);
  1901. if (slot == nullptr) {
  1902. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1903. break;
  1904. }
  1905. if (slot->is_processing()) {
  1906. // if requested slot is unavailable, we defer this task for processing later
  1907. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1908. queue_tasks.defer(task);
  1909. break;
  1910. }
  1911. const int64_t t_start = ggml_time_us();
  1912. std::string filename = task.data.at("filename");
  1913. std::string filepath = task.data.at("filepath");
  1914. slot->cache_tokens.resize(slot->n_ctx);
  1915. size_t token_count = 0;
  1916. size_t nread = llama_state_seq_load_file(ctx, filepath.c_str(), slot->id, slot->cache_tokens.data(), slot->cache_tokens.size(), &token_count);
  1917. if (nread == 0) {
  1918. slot->cache_tokens.resize(0);
  1919. send_error(task, "Unable to restore slot, no available space in KV cache or invalid slot save file", ERROR_TYPE_INVALID_REQUEST);
  1920. break;
  1921. }
  1922. slot->cache_tokens.resize(token_count);
  1923. const int64_t t_end = ggml_time_us();
  1924. const double t_restore_ms = (t_end - t_start) / 1000.0;
  1925. auto res = std::make_unique<server_task_result_slot_save_load>();
  1926. res->id = task.id;
  1927. res->id_slot = id_slot;
  1928. res->filename = filename;
  1929. res->is_save = false;
  1930. res->n_tokens = token_count;
  1931. res->n_bytes = nread;
  1932. res->t_ms = t_restore_ms;
  1933. queue_results.send(std::move(res));
  1934. } break;
  1935. case SERVER_TASK_TYPE_SLOT_ERASE:
  1936. {
  1937. int id_slot = task.data.at("id_slot");
  1938. server_slot * slot = get_slot_by_id(id_slot);
  1939. if (slot == nullptr) {
  1940. send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST);
  1941. break;
  1942. }
  1943. if (slot->is_processing()) {
  1944. // if requested slot is unavailable, we defer this task for processing later
  1945. SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id);
  1946. queue_tasks.defer(task);
  1947. break;
  1948. }
  1949. // Erase token cache
  1950. const size_t n_erased = slot->cache_tokens.size();
  1951. llama_kv_cache_seq_rm(ctx, slot->id, -1, -1);
  1952. slot->cache_tokens.clear();
  1953. auto res = std::make_unique<server_task_result_slot_erase>();
  1954. res->id = task.id;
  1955. res->id_slot = id_slot;
  1956. res->n_erased = n_erased;
  1957. queue_results.send(std::move(res));
  1958. } break;
  1959. case SERVER_TASK_TYPE_SET_LORA:
  1960. {
  1961. common_lora_adapters_apply(ctx, loras);
  1962. auto res = std::make_unique<server_task_result_apply_lora>();
  1963. res->id = task.id;
  1964. queue_results.send(std::move(res));
  1965. } break;
  1966. }
  1967. }
  1968. void update_slots() {
  1969. // check if all slots are idle
  1970. {
  1971. bool all_idle = true;
  1972. for (auto & slot : slots) {
  1973. if (slot.is_processing()) {
  1974. all_idle = false;
  1975. break;
  1976. }
  1977. }
  1978. if (all_idle) {
  1979. SRV_INF("%s", "all slots are idle\n");
  1980. if (clean_kv_cache) {
  1981. kv_cache_clear();
  1982. }
  1983. return;
  1984. }
  1985. }
  1986. {
  1987. SRV_DBG("%s", "posting NEXT_RESPONSE\n");
  1988. server_task task;
  1989. task.type = SERVER_TASK_TYPE_NEXT_RESPONSE;
  1990. task.id_target = -1;
  1991. queue_tasks.post(task);
  1992. }
  1993. // apply context-shift if needed
  1994. // TODO: simplify and improve
  1995. for (server_slot & slot : slots) {
  1996. if (slot.is_processing() && slot.n_past + 1 >= slot.n_ctx) {
  1997. if (!params_base.ctx_shift) {
  1998. // this check is redundant (for good)
  1999. // we should never get here, because generation should already stopped in process_token()
  2000. slot.release();
  2001. send_error(slot, "context shift is disabled", ERROR_TYPE_SERVER);
  2002. continue;
  2003. }
  2004. // Shift context
  2005. const int n_keep = slot.params.n_keep + add_bos_token;
  2006. const int n_left = slot.n_past - n_keep;
  2007. const int n_discard = slot.params.n_discard ? slot.params.n_discard : (n_left / 2);
  2008. SLT_WRN(slot, "slot context shift, n_keep = %d, n_left = %d, n_discard = %d\n", n_keep, n_left, n_discard);
  2009. llama_kv_cache_seq_rm (ctx, slot.id, n_keep , n_keep + n_discard);
  2010. llama_kv_cache_seq_add(ctx, slot.id, n_keep + n_discard, slot.n_past, -n_discard);
  2011. if (slot.params.cache_prompt) {
  2012. for (size_t i = n_keep + n_discard; i < slot.cache_tokens.size(); i++) {
  2013. slot.cache_tokens[i - n_discard] = slot.cache_tokens[i];
  2014. }
  2015. slot.cache_tokens.resize(slot.cache_tokens.size() - n_discard);
  2016. }
  2017. slot.n_past -= n_discard;
  2018. slot.truncated = true;
  2019. }
  2020. }
  2021. // start populating the batch for this iteration
  2022. common_batch_clear(batch);
  2023. // frist, add sampled tokens from any ongoing sequences
  2024. for (auto & slot : slots) {
  2025. if (slot.state != SLOT_STATE_GENERATING) {
  2026. continue;
  2027. }
  2028. slot.i_batch = batch.n_tokens;
  2029. common_batch_add(batch, slot.sampled, slot.n_past, { slot.id }, true);
  2030. slot.n_past += 1;
  2031. if (slot.params.cache_prompt) {
  2032. slot.cache_tokens.push_back(slot.sampled);
  2033. }
  2034. SLT_DBG(slot, "slot decode token, n_ctx = %d, n_past = %d, n_cache_tokens = %d, truncated = %d\n",
  2035. slot.n_ctx, slot.n_past, (int) slot.cache_tokens.size(), slot.truncated);
  2036. }
  2037. // process in chunks of params.n_batch
  2038. int32_t n_batch = llama_n_batch(ctx);
  2039. int32_t n_ubatch = llama_n_ubatch(ctx);
  2040. // track if this is an embedding or non-embedding batch
  2041. // if we've added sampled tokens above, we are in non-embedding mode
  2042. // -1: none, 0: non-embedding, 1: embedding
  2043. // TODO: make enum
  2044. int32_t batch_type = batch.n_tokens > 0 ? 0 : -1;
  2045. // next, batch any pending prompts without exceeding n_batch
  2046. if (params_base.cont_batching || batch.n_tokens == 0) {
  2047. for (auto & slot : slots) {
  2048. // this slot still has a prompt to be processed
  2049. if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_STARTED) {
  2050. auto & prompt_tokens = slot.prompt_tokens;
  2051. // TODO: maybe move branch to outside of this loop in the future
  2052. if (slot.state == SLOT_STATE_STARTED) {
  2053. slot.t_start_process_prompt = ggml_time_us();
  2054. slot.t_start_generation = 0;
  2055. slot.n_past = 0;
  2056. slot.n_prompt_tokens = prompt_tokens.size();
  2057. slot.state = SLOT_STATE_PROCESSING_PROMPT;
  2058. SLT_INF(slot, "new prompt, n_ctx_slot = %d, n_keep = %d, n_prompt_tokens = %d\n", slot.n_ctx, slot.params.n_keep, slot.n_prompt_tokens);
  2059. // print prompt tokens (for debugging)
  2060. if (1) {
  2061. // first 16 tokens (avoid flooding logs)
  2062. for (int i = 0; i < std::min<int>(16, prompt_tokens.size()); i++) {
  2063. SLT_DBG(slot, "prompt token %3d: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  2064. }
  2065. } else {
  2066. // all
  2067. for (int i = 0; i < (int) prompt_tokens.size(); i++) {
  2068. SLT_DBG(slot, "prompt token %3d: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  2069. }
  2070. }
  2071. // empty prompt passed -> release the slot and send empty response
  2072. if (prompt_tokens.empty()) {
  2073. SLT_WRN(slot, "%s", "empty prompt - releasing slot\n");
  2074. slot.release();
  2075. slot.print_timings();
  2076. send_final_response(slot);
  2077. continue;
  2078. }
  2079. if (slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING || slot.inf_type == SERVER_TASK_INF_TYPE_RERANK) {
  2080. if (slot.n_prompt_tokens > n_ubatch) {
  2081. slot.release();
  2082. send_error(slot, "input is too large to process. increase the physical batch size", ERROR_TYPE_SERVER);
  2083. continue;
  2084. }
  2085. if (slot.n_prompt_tokens > slot.n_ctx) {
  2086. slot.release();
  2087. send_error(slot, "input is larger than the max context size. skipping", ERROR_TYPE_SERVER);
  2088. continue;
  2089. }
  2090. } else {
  2091. if (!params_base.ctx_shift) {
  2092. // if context shift is disabled, we make sure prompt size is smaller than KV size
  2093. // TODO: there should be a separate parameter that control prompt truncation
  2094. // context shift should be applied only during the generation phase
  2095. if (slot.n_prompt_tokens >= slot.n_ctx) {
  2096. slot.release();
  2097. send_error(slot, "the request exceeds the available context size. try increasing the context size or enable context shift", ERROR_TYPE_INVALID_REQUEST);
  2098. continue;
  2099. }
  2100. }
  2101. if (slot.params.n_keep < 0) {
  2102. slot.params.n_keep = slot.n_prompt_tokens;
  2103. }
  2104. slot.params.n_keep = std::min(slot.n_ctx - 4, slot.params.n_keep);
  2105. // if input prompt is too big, truncate it
  2106. if (slot.n_prompt_tokens >= slot.n_ctx) {
  2107. const int n_left = slot.n_ctx - slot.params.n_keep;
  2108. const int n_block_size = n_left / 2;
  2109. const int erased_blocks = (slot.n_prompt_tokens - slot.params.n_keep - n_block_size) / n_block_size;
  2110. llama_tokens new_tokens(
  2111. prompt_tokens.begin(),
  2112. prompt_tokens.begin() + slot.params.n_keep);
  2113. new_tokens.insert(
  2114. new_tokens.end(),
  2115. prompt_tokens.begin() + slot.params.n_keep + erased_blocks * n_block_size,
  2116. prompt_tokens.end());
  2117. prompt_tokens = std::move(new_tokens);
  2118. slot.truncated = true;
  2119. slot.n_prompt_tokens = prompt_tokens.size();
  2120. SLT_WRN(slot, "input truncated, n_ctx = %d, n_keep = %d, n_left = %d, n_prompt_tokens = %d\n", slot.n_ctx, slot.params.n_keep, n_left, slot.n_prompt_tokens);
  2121. GGML_ASSERT(slot.n_prompt_tokens < slot.n_ctx);
  2122. }
  2123. if (slot.params.cache_prompt) {
  2124. // reuse any previously computed tokens that are common with the new prompt
  2125. slot.n_past = common_lcp(slot.cache_tokens, prompt_tokens);
  2126. // reuse chunks from the cached prompt by shifting their KV cache in the new position
  2127. if (params_base.n_cache_reuse > 0) {
  2128. size_t head_c = slot.n_past; // cache
  2129. size_t head_p = slot.n_past; // current prompt
  2130. SLT_DBG(slot, "trying to reuse chunks with size > %d, slot.n_past = %d\n", params_base.n_cache_reuse, slot.n_past);
  2131. while (head_c < slot.cache_tokens.size() &&
  2132. head_p < prompt_tokens.size()) {
  2133. size_t n_match = 0;
  2134. while (head_c + n_match < slot.cache_tokens.size() &&
  2135. head_p + n_match < prompt_tokens.size() &&
  2136. slot.cache_tokens[head_c + n_match] == prompt_tokens[head_p + n_match]) {
  2137. n_match++;
  2138. }
  2139. if (n_match >= (size_t) params_base.n_cache_reuse) {
  2140. SLT_INF(slot, "reusing chunk with size %zu, shifting KV cache [%zu, %zu) -> [%zu, %zu)\n", n_match, head_c, head_c + n_match, head_p, head_p + n_match);
  2141. //for (size_t i = head_p; i < head_p + n_match; i++) {
  2142. // SLT_DBG(slot, "cache token %3zu: %6d '%s'\n", i, prompt_tokens[i], common_token_to_piece(ctx, prompt_tokens[i]).c_str());
  2143. //}
  2144. const int64_t kv_shift = (int64_t) head_p - (int64_t) head_c;
  2145. llama_kv_cache_seq_rm (ctx, slot.id, head_p, head_c);
  2146. llama_kv_cache_seq_add(ctx, slot.id, head_c, -1, kv_shift);
  2147. for (size_t i = 0; i < n_match; i++) {
  2148. slot.cache_tokens[head_p + i] = slot.cache_tokens[head_c + i];
  2149. slot.n_past++;
  2150. }
  2151. head_c += n_match;
  2152. head_p += n_match;
  2153. } else {
  2154. head_c += 1;
  2155. }
  2156. }
  2157. SLT_DBG(slot, "after context reuse, new slot.n_past = %d\n", slot.n_past);
  2158. }
  2159. }
  2160. }
  2161. if (slot.n_past == slot.n_prompt_tokens && slot.n_past > 0) {
  2162. // we have to evaluate at least 1 token to generate logits.
  2163. SLT_WRN(slot, "need to evaluate at least 1 token to generate logits, n_past = %d, n_prompt_tokens = %d\n", slot.n_past, slot.n_prompt_tokens);
  2164. slot.n_past--;
  2165. }
  2166. slot.n_prompt_tokens_processed = 0;
  2167. }
  2168. // non-causal tasks require to fit the entire prompt in the physical batch
  2169. if (slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING || slot.inf_type == SERVER_TASK_INF_TYPE_RERANK) {
  2170. // cannot fit the prompt in the current batch - will try next iter
  2171. if (batch.n_tokens + slot.n_prompt_tokens > n_batch) {
  2172. continue;
  2173. }
  2174. }
  2175. // check that we are in the right batch_type, if not defer the slot
  2176. const bool slot_type =
  2177. slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING ||
  2178. slot.inf_type == SERVER_TASK_INF_TYPE_RERANK ? 1 : 0;
  2179. if (batch_type == -1) {
  2180. batch_type = slot_type;
  2181. } else if (batch_type != slot_type) {
  2182. continue;
  2183. }
  2184. // keep only the common part
  2185. if (!llama_kv_cache_seq_rm(ctx, slot.id, slot.n_past, -1)) {
  2186. // could not partially delete (likely using a non-Transformer model)
  2187. llama_kv_cache_seq_rm(ctx, slot.id, -1, -1);
  2188. // there is no common part left
  2189. slot.n_past = 0;
  2190. }
  2191. SLT_INF(slot, "kv cache rm [%d, end)\n", slot.n_past);
  2192. // remove the non-common part from the cache
  2193. slot.cache_tokens.resize(slot.n_past);
  2194. // add prompt tokens for processing in the current batch
  2195. while (slot.n_past < slot.n_prompt_tokens && batch.n_tokens < n_batch) {
  2196. common_batch_add(batch, prompt_tokens[slot.n_past], slot.n_past, { slot.id }, false);
  2197. if (slot.params.cache_prompt) {
  2198. slot.cache_tokens.push_back(prompt_tokens[slot.n_past]);
  2199. }
  2200. slot.n_prompt_tokens_processed++;
  2201. slot.n_past++;
  2202. }
  2203. SLT_INF(slot, "prompt processing progress, n_past = %d, n_tokens = %d, progress = %f\n", slot.n_past, batch.n_tokens, (float) slot.n_prompt_tokens_processed / slot.n_prompt_tokens);
  2204. // entire prompt has been processed
  2205. if (slot.n_past == slot.n_prompt_tokens) {
  2206. slot.state = SLOT_STATE_DONE_PROMPT;
  2207. GGML_ASSERT(batch.n_tokens > 0);
  2208. common_sampler_reset(slot.smpl);
  2209. // Process all prompt tokens through sampler system
  2210. for (int i = 0; i < slot.n_prompt_tokens; ++i) {
  2211. common_sampler_accept(slot.smpl, prompt_tokens[i], false);
  2212. }
  2213. // extract the logits only for the last token
  2214. batch.logits[batch.n_tokens - 1] = true;
  2215. slot.n_decoded = 0;
  2216. slot.i_batch = batch.n_tokens - 1;
  2217. SLT_INF(slot, "prompt done, n_past = %d, n_tokens = %d\n", slot.n_past, batch.n_tokens);
  2218. }
  2219. }
  2220. if (batch.n_tokens >= n_batch) {
  2221. break;
  2222. }
  2223. }
  2224. }
  2225. if (batch.n_tokens == 0) {
  2226. SRV_WRN("%s", "no tokens to decode\n");
  2227. return;
  2228. }
  2229. SRV_DBG("decoding batch, n_tokens = %d\n", batch.n_tokens);
  2230. // make sure we're in the right embedding mode
  2231. llama_set_embeddings(ctx, batch_type == 1);
  2232. // process the created batch of tokens
  2233. for (int32_t i = 0; i < batch.n_tokens; i += n_batch) {
  2234. const int32_t n_tokens = std::min(n_batch, batch.n_tokens - i);
  2235. llama_batch batch_view = {
  2236. n_tokens,
  2237. batch.token + i,
  2238. nullptr,
  2239. batch.pos + i,
  2240. batch.n_seq_id + i,
  2241. batch.seq_id + i,
  2242. batch.logits + i,
  2243. };
  2244. const int ret = llama_decode(ctx, batch_view);
  2245. metrics.on_decoded(slots);
  2246. if (ret != 0) {
  2247. if (n_batch == 1 || ret < 0) {
  2248. // if you get here, it means the KV cache is full - try increasing it via the context size
  2249. SRV_ERR("failed to decode the batch: KV cache is full - try increasing it via the context size, i = %d, n_batch = %d, ret = %d\n", i, n_batch, ret);
  2250. for (auto & slot : slots) {
  2251. slot.release();
  2252. send_error(slot, "Input prompt is too big compared to KV size. Please try increasing KV size.");
  2253. }
  2254. break; // break loop of n_batch
  2255. }
  2256. // retry with half the batch size to try to find a free slot in the KV cache
  2257. n_batch /= 2;
  2258. i -= n_batch;
  2259. SRV_WRN("failed to find free space in the KV cache, retrying with smaller batch size - try increasing it via the context size or enable defragmentation, i = %d, n_batch = %d, ret = %d\n", i, n_batch, ret);
  2260. continue; // continue loop of n_batch
  2261. }
  2262. for (auto & slot : slots) {
  2263. if (slot.i_batch < (int) i || slot.i_batch >= (int) (i + n_tokens)) {
  2264. continue; // continue loop of slots
  2265. }
  2266. if (slot.state == SLOT_STATE_DONE_PROMPT) {
  2267. if (slot.inf_type == SERVER_TASK_INF_TYPE_EMBEDDING) {
  2268. // prompt evaluated for embedding
  2269. send_embedding(slot, batch_view);
  2270. slot.release();
  2271. slot.i_batch = -1;
  2272. continue; // continue loop of slots
  2273. }
  2274. if (slot.inf_type == SERVER_TASK_INF_TYPE_RERANK) {
  2275. send_rerank(slot, batch_view);
  2276. slot.release();
  2277. slot.i_batch = -1;
  2278. continue; // continue loop of slots
  2279. }
  2280. // prompt evaluated for next-token prediction
  2281. slot.state = SLOT_STATE_GENERATING;
  2282. } else if (slot.state != SLOT_STATE_GENERATING) {
  2283. continue; // continue loop of slots
  2284. }
  2285. llama_token id = common_sampler_sample(slot.smpl, ctx, slot.i_batch - i);
  2286. slot.i_batch = -1;
  2287. common_sampler_accept(slot.smpl, id, true);
  2288. slot.n_decoded += 1;
  2289. const int64_t t_current = ggml_time_us();
  2290. if (slot.n_decoded == 1) {
  2291. slot.t_start_generation = t_current;
  2292. slot.t_prompt_processing = (slot.t_start_generation - slot.t_start_process_prompt) / 1e3;
  2293. metrics.on_prompt_eval(slot);
  2294. }
  2295. slot.t_token_generation = (t_current - slot.t_start_generation) / 1e3;
  2296. completion_token_output result;
  2297. result.tok = id;
  2298. const auto * cur_p = common_sampler_get_candidates(slot.smpl);
  2299. for (size_t i = 0; i < (size_t) slot.params.sampling.n_probs; ++i) {
  2300. auto tok_id = cur_p->data[i].id;
  2301. result.probs.push_back({
  2302. tok_id,
  2303. tokens_to_output_formatted_string(ctx, tok_id),
  2304. i >= cur_p->size ? 0.0f : cur_p->data[i].p,
  2305. });
  2306. }
  2307. if (!process_token(result, slot)) {
  2308. // release slot because of stop condition
  2309. slot.release();
  2310. slot.print_timings();
  2311. send_final_response(slot);
  2312. metrics.on_prediction(slot);
  2313. continue;
  2314. }
  2315. }
  2316. // do speculative decoding
  2317. for (auto & slot : slots) {
  2318. if (!slot.is_processing() || !slot.can_speculate()) {
  2319. continue;
  2320. }
  2321. if (slot.state != SLOT_STATE_GENERATING) {
  2322. continue;
  2323. }
  2324. // determine the max draft that fits the current slot state
  2325. int n_draft_max = slot.params.speculative.n_max;
  2326. // note: n_past is not yet increased for the `id` token sampled above
  2327. // also, need to leave space for 1 extra token to allow context shifts
  2328. n_draft_max = std::min(n_draft_max, slot.n_ctx - slot.n_past - 2);
  2329. if (slot.n_remaining > 0) {
  2330. n_draft_max = std::min(n_draft_max, slot.n_remaining - 1);
  2331. }
  2332. SLT_DBG(slot, "max possible draft: %d\n", n_draft_max);
  2333. if (n_draft_max < slot.params.speculative.n_min) {
  2334. SLT_DBG(slot, "the max possible draft is too small: %d < %d - skipping speculative decoding\n", n_draft_max, slot.params.speculative.n_min);
  2335. continue;
  2336. }
  2337. llama_token id = slot.sampled;
  2338. struct common_speculative_params params_spec;
  2339. params_spec.n_draft = n_draft_max;
  2340. params_spec.n_reuse = llama_n_ctx(slot.ctx_dft) - slot.params.speculative.n_max;
  2341. params_spec.p_min = slot.params.speculative.p_min;
  2342. llama_tokens draft = common_speculative_gen_draft(slot.spec, params_spec, slot.cache_tokens, id);
  2343. // ignore small drafts
  2344. if (slot.params.speculative.n_min > (int) draft.size()) {
  2345. SLT_DBG(slot, "ignoring small draft: %d < %d\n", (int) draft.size(), slot.params.speculative.n_min);
  2346. continue;
  2347. }
  2348. // construct the speculation batch
  2349. common_batch_clear(slot.batch_spec);
  2350. common_batch_add (slot.batch_spec, id, slot.n_past, { slot.id }, true);
  2351. for (size_t i = 0; i < draft.size(); ++i) {
  2352. common_batch_add(slot.batch_spec, draft[i], slot.n_past + 1 + i, { slot.id }, true);
  2353. }
  2354. SLT_DBG(slot, "decoding speculative batch, size = %d\n", slot.batch_spec.n_tokens);
  2355. llama_decode(ctx, slot.batch_spec);
  2356. // the accepted tokens from the speculation
  2357. const auto ids = common_sampler_sample_and_accept_n(slot.smpl, ctx, draft);
  2358. slot.n_past += ids.size();
  2359. slot.n_decoded += ids.size();
  2360. slot.cache_tokens.push_back(id);
  2361. slot.cache_tokens.insert(slot.cache_tokens.end(), ids.begin(), ids.end() - 1);
  2362. llama_kv_cache_seq_rm(ctx, slot.id, slot.n_past, -1);
  2363. for (size_t i = 0; i < ids.size(); ++i) {
  2364. completion_token_output result;
  2365. result.tok = ids[i];
  2366. if (!process_token(result, slot)) {
  2367. // release slot because of stop condition
  2368. slot.release();
  2369. slot.print_timings();
  2370. send_final_response(slot);
  2371. metrics.on_prediction(slot);
  2372. break;
  2373. }
  2374. }
  2375. SLT_DBG(slot, "accepted %d/%d draft tokens, new n_past = %d\n", (int) ids.size() - 1, (int) draft.size(), slot.n_past);
  2376. }
  2377. }
  2378. SRV_DBG("%s", "run slots completed\n");
  2379. }
  2380. json model_meta() const {
  2381. return json {
  2382. {"vocab_type", llama_vocab_type (model)},
  2383. {"n_vocab", llama_n_vocab (model)},
  2384. {"n_ctx_train", llama_n_ctx_train (model)},
  2385. {"n_embd", llama_n_embd (model)},
  2386. {"n_params", llama_model_n_params(model)},
  2387. {"size", llama_model_size (model)},
  2388. };
  2389. }
  2390. };
  2391. static void log_server_request(const httplib::Request & req, const httplib::Response & res) {
  2392. // skip GH copilot requests when using default port
  2393. if (req.path == "/v1/health" || req.path == "/v1/completions") {
  2394. return;
  2395. }
  2396. LOG_INF("request: %s %s %s %d\n", req.method.c_str(), req.path.c_str(), req.remote_addr.c_str(), res.status);
  2397. LOG_DBG("request: %s\n", req.body.c_str());
  2398. LOG_DBG("response: %s\n", res.body.c_str());
  2399. }
  2400. std::function<void(int)> shutdown_handler;
  2401. std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
  2402. inline void signal_handler(int signal) {
  2403. if (is_terminating.test_and_set()) {
  2404. // in case it hangs, we can force terminate the server by hitting Ctrl+C twice
  2405. // this is for better developer experience, we can remove when the server is stable enough
  2406. fprintf(stderr, "Received second interrupt, terminating immediately.\n");
  2407. exit(1);
  2408. }
  2409. shutdown_handler(signal);
  2410. }
  2411. int main(int argc, char ** argv) {
  2412. // own arguments required by this example
  2413. common_params params;
  2414. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_SERVER)) {
  2415. return 1;
  2416. }
  2417. common_init();
  2418. // struct that contains llama context and inference
  2419. server_context ctx_server;
  2420. llama_backend_init();
  2421. llama_numa_init(params.numa);
  2422. LOG_INF("system info: n_threads = %d, n_threads_batch = %d, total_threads = %d\n", params.cpuparams.n_threads, params.cpuparams_batch.n_threads, std::thread::hardware_concurrency());
  2423. LOG_INF("\n");
  2424. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  2425. LOG_INF("\n");
  2426. std::unique_ptr<httplib::Server> svr;
  2427. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2428. if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
  2429. LOG_INF("Running with SSL: key = %s, cert = %s\n", params.ssl_file_key.c_str(), params.ssl_file_cert.c_str());
  2430. svr.reset(
  2431. new httplib::SSLServer(params.ssl_file_cert.c_str(), params.ssl_file_key.c_str())
  2432. );
  2433. } else {
  2434. LOG_INF("Running without SSL\n");
  2435. svr.reset(new httplib::Server());
  2436. }
  2437. #else
  2438. if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
  2439. LOG_ERR("Server is built without SSL support\n");
  2440. return 1;
  2441. }
  2442. svr.reset(new httplib::Server());
  2443. #endif
  2444. std::atomic<server_state> state{SERVER_STATE_LOADING_MODEL};
  2445. svr->set_default_headers({{"Server", "llama.cpp"}});
  2446. svr->set_logger(log_server_request);
  2447. auto res_error = [](httplib::Response & res, const json & error_data) {
  2448. json final_response {{"error", error_data}};
  2449. res.set_content(final_response.dump(-1, ' ', false, json::error_handler_t::replace), MIMETYPE_JSON);
  2450. res.status = json_value(error_data, "code", 500);
  2451. };
  2452. auto res_ok = [](httplib::Response & res, const json & data) {
  2453. res.set_content(data.dump(-1, ' ', false, json::error_handler_t::replace), MIMETYPE_JSON);
  2454. res.status = 200;
  2455. };
  2456. svr->set_exception_handler([&res_error](const httplib::Request &, httplib::Response & res, std::exception_ptr ep) {
  2457. std::string message;
  2458. try {
  2459. std::rethrow_exception(ep);
  2460. } catch (std::exception & e) {
  2461. message = e.what();
  2462. } catch (...) {
  2463. message = "Unknown Exception";
  2464. }
  2465. json formatted_error = format_error_response(message, ERROR_TYPE_SERVER);
  2466. LOG_WRN("got exception: %s\n", formatted_error.dump().c_str());
  2467. res_error(res, formatted_error);
  2468. });
  2469. svr->set_error_handler([&res_error](const httplib::Request &, httplib::Response & res) {
  2470. if (res.status == 404) {
  2471. res_error(res, format_error_response("File Not Found", ERROR_TYPE_NOT_FOUND));
  2472. }
  2473. // for other error codes, we skip processing here because it's already done by res_error()
  2474. });
  2475. // set timeouts and change hostname and port
  2476. svr->set_read_timeout (params.timeout_read);
  2477. svr->set_write_timeout(params.timeout_write);
  2478. std::unordered_map<std::string, std::string> log_data;
  2479. log_data["hostname"] = params.hostname;
  2480. log_data["port"] = std::to_string(params.port);
  2481. if (params.api_keys.size() == 1) {
  2482. auto key = params.api_keys[0];
  2483. log_data["api_key"] = "api_key: ****" + key.substr(std::max((int)(key.length() - 4), 0));
  2484. } else if (params.api_keys.size() > 1) {
  2485. log_data["api_key"] = "api_key: " + std::to_string(params.api_keys.size()) + " keys loaded";
  2486. }
  2487. // Necessary similarity of prompt for slot selection
  2488. ctx_server.slot_prompt_similarity = params.slot_prompt_similarity;
  2489. //
  2490. // Middlewares
  2491. //
  2492. auto middleware_validate_api_key = [&params, &res_error](const httplib::Request & req, httplib::Response & res) {
  2493. static const std::unordered_set<std::string> public_endpoints = {
  2494. "/health",
  2495. "/models",
  2496. "/v1/models",
  2497. };
  2498. // If API key is not set, skip validation
  2499. if (params.api_keys.empty()) {
  2500. return true;
  2501. }
  2502. // If path is public or is static file, skip validation
  2503. if (public_endpoints.find(req.path) != public_endpoints.end() || req.path == "/") {
  2504. return true;
  2505. }
  2506. // Check for API key in the header
  2507. auto auth_header = req.get_header_value("Authorization");
  2508. std::string prefix = "Bearer ";
  2509. if (auth_header.substr(0, prefix.size()) == prefix) {
  2510. std::string received_api_key = auth_header.substr(prefix.size());
  2511. if (std::find(params.api_keys.begin(), params.api_keys.end(), received_api_key) != params.api_keys.end()) {
  2512. return true; // API key is valid
  2513. }
  2514. }
  2515. // API key is invalid or not provided
  2516. res_error(res, format_error_response("Invalid API Key", ERROR_TYPE_AUTHENTICATION));
  2517. LOG_WRN("Unauthorized: Invalid API Key\n");
  2518. return false;
  2519. };
  2520. auto middleware_server_state = [&res_error, &state](const httplib::Request & req, httplib::Response & res) {
  2521. server_state current_state = state.load();
  2522. if (current_state == SERVER_STATE_LOADING_MODEL) {
  2523. auto tmp = string_split<std::string>(req.path, '.');
  2524. if (req.path == "/" || tmp.back() == "html") {
  2525. res.set_content(reinterpret_cast<const char*>(loading_html), loading_html_len, "text/html; charset=utf-8");
  2526. res.status = 503;
  2527. } else {
  2528. res_error(res, format_error_response("Loading model", ERROR_TYPE_UNAVAILABLE));
  2529. }
  2530. return false;
  2531. }
  2532. return true;
  2533. };
  2534. // register server middlewares
  2535. svr->set_pre_routing_handler([&middleware_validate_api_key, &middleware_server_state](const httplib::Request & req, httplib::Response & res) {
  2536. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  2537. // If this is OPTIONS request, skip validation because browsers don't include Authorization header
  2538. if (req.method == "OPTIONS") {
  2539. res.set_header("Access-Control-Allow-Credentials", "true");
  2540. res.set_header("Access-Control-Allow-Methods", "GET, POST");
  2541. res.set_header("Access-Control-Allow-Headers", "*");
  2542. res.set_content("", "text/html"); // blank response, no data
  2543. return httplib::Server::HandlerResponse::Handled; // skip further processing
  2544. }
  2545. if (!middleware_server_state(req, res)) {
  2546. return httplib::Server::HandlerResponse::Handled;
  2547. }
  2548. if (!middleware_validate_api_key(req, res)) {
  2549. return httplib::Server::HandlerResponse::Handled;
  2550. }
  2551. return httplib::Server::HandlerResponse::Unhandled;
  2552. });
  2553. //
  2554. // Route handlers (or controllers)
  2555. //
  2556. const auto handle_health = [&](const httplib::Request &, httplib::Response & res) {
  2557. // error and loading states are handled by middleware
  2558. json health = {{"status", "ok"}};
  2559. res_ok(res, health);
  2560. };
  2561. const auto handle_slots = [&](const httplib::Request & req, httplib::Response & res) {
  2562. if (!params.endpoint_slots) {
  2563. res_error(res, format_error_response("This server does not support slots endpoint. Start it with `--slots`", ERROR_TYPE_NOT_SUPPORTED));
  2564. return;
  2565. }
  2566. // request slots data using task queue
  2567. server_task task;
  2568. task.id = ctx_server.queue_tasks.get_new_id();
  2569. task.type = SERVER_TASK_TYPE_METRICS;
  2570. ctx_server.queue_results.add_waiting_task_id(task.id);
  2571. ctx_server.queue_tasks.post(task, true); // high-priority task
  2572. // get the result
  2573. server_task_result_ptr result = ctx_server.queue_results.recv(task.id);
  2574. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2575. if (result->is_error()) {
  2576. res_error(res, result->to_json());
  2577. return;
  2578. }
  2579. // TODO: get rid of this dynamic_cast
  2580. auto res_metrics = dynamic_cast<server_task_result_metrics*>(result.get());
  2581. GGML_ASSERT(res_metrics != nullptr);
  2582. // optionally return "fail_on_no_slot" error
  2583. if (req.has_param("fail_on_no_slot")) {
  2584. if (res_metrics->n_idle_slots == 0) {
  2585. res_error(res, format_error_response("no slot available", ERROR_TYPE_UNAVAILABLE));
  2586. return;
  2587. }
  2588. }
  2589. res_ok(res, res_metrics->slots_data);
  2590. };
  2591. const auto handle_metrics = [&](const httplib::Request &, httplib::Response & res) {
  2592. if (!params.endpoint_metrics) {
  2593. res_error(res, format_error_response("This server does not support metrics endpoint. Start it with `--metrics`", ERROR_TYPE_NOT_SUPPORTED));
  2594. return;
  2595. }
  2596. // request slots data using task queue
  2597. server_task task;
  2598. task.id = ctx_server.queue_tasks.get_new_id();
  2599. task.id_target = -1;
  2600. task.type = SERVER_TASK_TYPE_METRICS;
  2601. task.data.push_back({{"reset_bucket", true}});
  2602. ctx_server.queue_results.add_waiting_task_id(task.id);
  2603. ctx_server.queue_tasks.post(task, true); // high-priority task
  2604. // get the result
  2605. server_task_result_ptr result = ctx_server.queue_results.recv(task.id);
  2606. ctx_server.queue_results.remove_waiting_task_id(task.id);
  2607. if (result->is_error()) {
  2608. res_error(res, result->to_json());
  2609. return;
  2610. }
  2611. // TODO: get rid of this dynamic_cast
  2612. auto res_metrics = dynamic_cast<server_task_result_metrics*>(result.get());
  2613. GGML_ASSERT(res_metrics != nullptr);
  2614. // metrics definition: https://prometheus.io/docs/practices/naming/#metric-names
  2615. json all_metrics_def = json {
  2616. {"counter", {{
  2617. {"name", "prompt_tokens_total"},
  2618. {"help", "Number of prompt tokens processed."},
  2619. {"value", (uint64_t) res_metrics->n_prompt_tokens_processed_total}
  2620. }, {
  2621. {"name", "prompt_seconds_total"},
  2622. {"help", "Prompt process time"},
  2623. {"value", (uint64_t) res_metrics->t_prompt_processing_total / 1.e3}
  2624. }, {
  2625. {"name", "tokens_predicted_total"},
  2626. {"help", "Number of generation tokens processed."},
  2627. {"value", (uint64_t) res_metrics->n_tokens_predicted_total}
  2628. }, {
  2629. {"name", "tokens_predicted_seconds_total"},
  2630. {"help", "Predict process time"},
  2631. {"value", (uint64_t) res_metrics->t_tokens_generation_total / 1.e3}
  2632. }, {
  2633. {"name", "n_decode_total"},
  2634. {"help", "Total number of llama_decode() calls"},
  2635. {"value", res_metrics->n_decode_total}
  2636. }, {
  2637. {"name", "n_busy_slots_per_decode"},
  2638. {"help", "Average number of busy slots per llama_decode() call"},
  2639. {"value", (float) res_metrics->n_busy_slots_total / (float) res_metrics->n_decode_total}
  2640. }}},
  2641. {"gauge", {{
  2642. {"name", "prompt_tokens_seconds"},
  2643. {"help", "Average prompt throughput in tokens/s."},
  2644. {"value", res_metrics->n_prompt_tokens_processed ? 1.e3 / res_metrics->t_prompt_processing * res_metrics->n_prompt_tokens_processed : 0.}
  2645. },{
  2646. {"name", "predicted_tokens_seconds"},
  2647. {"help", "Average generation throughput in tokens/s."},
  2648. {"value", res_metrics->n_tokens_predicted ? 1.e3 / res_metrics->t_tokens_generation * res_metrics->n_tokens_predicted : 0.}
  2649. },{
  2650. {"name", "kv_cache_usage_ratio"},
  2651. {"help", "KV-cache usage. 1 means 100 percent usage."},
  2652. {"value", 1. * res_metrics->kv_cache_used_cells / params.n_ctx}
  2653. },{
  2654. {"name", "kv_cache_tokens"},
  2655. {"help", "KV-cache tokens."},
  2656. {"value", (uint64_t) res_metrics->kv_cache_tokens_count}
  2657. },{
  2658. {"name", "requests_processing"},
  2659. {"help", "Number of request processing."},
  2660. {"value", (uint64_t) res_metrics->n_processing_slots}
  2661. },{
  2662. {"name", "requests_deferred"},
  2663. {"help", "Number of request deferred."},
  2664. {"value", (uint64_t) res_metrics->n_tasks_deferred}
  2665. }}}
  2666. };
  2667. std::stringstream prometheus;
  2668. for (const auto & el : all_metrics_def.items()) {
  2669. const auto & type = el.key();
  2670. const auto & metrics_def = el.value();
  2671. for (const auto & metric_def : metrics_def) {
  2672. const std::string name = metric_def.at("name");
  2673. const std::string help = metric_def.at("help");
  2674. auto value = json_value(metric_def, "value", 0.);
  2675. prometheus << "# HELP llamacpp:" << name << " " << help << "\n"
  2676. << "# TYPE llamacpp:" << name << " " << type << "\n"
  2677. << "llamacpp:" << name << " " << value << "\n";
  2678. }
  2679. }
  2680. res.set_header("Process-Start-Time-Unix", std::to_string(res_metrics->t_start));
  2681. res.set_content(prometheus.str(), "text/plain; version=0.0.4");
  2682. res.status = 200; // HTTP OK
  2683. };
  2684. const auto handle_slots_save = [&ctx_server, &res_error, &res_ok, &params](const httplib::Request & req, httplib::Response & res, int id_slot) {
  2685. json request_data = json::parse(req.body);
  2686. std::string filename = request_data.at("filename");
  2687. if (!fs_validate_filename(filename)) {
  2688. res_error(res, format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  2689. return;
  2690. }
  2691. std::string filepath = params.slot_save_path + filename;
  2692. server_task task;
  2693. task.type = SERVER_TASK_TYPE_SLOT_SAVE;
  2694. task.data = {
  2695. { "id_slot", id_slot },
  2696. { "filename", filename },
  2697. { "filepath", filepath },
  2698. };
  2699. const int id_task = ctx_server.queue_tasks.post(task);
  2700. ctx_server.queue_results.add_waiting_task_id(id_task);
  2701. server_task_result_ptr result = ctx_server.queue_results.recv(id_task);
  2702. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2703. if (result->is_error()) {
  2704. res_error(res, result->to_json());
  2705. return;
  2706. }
  2707. res_ok(res, result->to_json());
  2708. };
  2709. const auto handle_slots_restore = [&ctx_server, &res_error, &res_ok, &params](const httplib::Request & req, httplib::Response & res, int id_slot) {
  2710. json request_data = json::parse(req.body);
  2711. std::string filename = request_data.at("filename");
  2712. if (!fs_validate_filename(filename)) {
  2713. res_error(res, format_error_response("Invalid filename", ERROR_TYPE_INVALID_REQUEST));
  2714. return;
  2715. }
  2716. std::string filepath = params.slot_save_path + filename;
  2717. server_task task;
  2718. task.type = SERVER_TASK_TYPE_SLOT_RESTORE;
  2719. task.data = {
  2720. { "id_slot", id_slot },
  2721. { "filename", filename },
  2722. { "filepath", filepath },
  2723. };
  2724. const int id_task = ctx_server.queue_tasks.post(task);
  2725. ctx_server.queue_results.add_waiting_task_id(id_task);
  2726. server_task_result_ptr result = ctx_server.queue_results.recv(id_task);
  2727. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2728. if (result->is_error()) {
  2729. res_error(res, result->to_json());
  2730. return;
  2731. }
  2732. GGML_ASSERT(dynamic_cast<server_task_result_slot_save_load*>(result.get()) != nullptr);
  2733. res_ok(res, result->to_json());
  2734. };
  2735. const auto handle_slots_erase = [&ctx_server, &res_error, &res_ok](const httplib::Request & /* req */, httplib::Response & res, int id_slot) {
  2736. server_task task;
  2737. task.type = SERVER_TASK_TYPE_SLOT_ERASE;
  2738. task.data = {
  2739. { "id_slot", id_slot },
  2740. };
  2741. const int id_task = ctx_server.queue_tasks.post(task);
  2742. ctx_server.queue_results.add_waiting_task_id(id_task);
  2743. server_task_result_ptr result = ctx_server.queue_results.recv(id_task);
  2744. ctx_server.queue_results.remove_waiting_task_id(id_task);
  2745. if (result->is_error()) {
  2746. res_error(res, result->to_json());
  2747. return;
  2748. }
  2749. GGML_ASSERT(dynamic_cast<server_task_result_slot_erase*>(result.get()) != nullptr);
  2750. res_ok(res, result->to_json());
  2751. };
  2752. const auto handle_slots_action = [&params, &res_error, &handle_slots_save, &handle_slots_restore, &handle_slots_erase](const httplib::Request & req, httplib::Response & res) {
  2753. if (params.slot_save_path.empty()) {
  2754. res_error(res, format_error_response("This server does not support slots action. Start it with `--slot-save-path`", ERROR_TYPE_NOT_SUPPORTED));
  2755. return;
  2756. }
  2757. std::string id_slot_str = req.path_params.at("id_slot");
  2758. int id_slot;
  2759. try {
  2760. id_slot = std::stoi(id_slot_str);
  2761. } catch (const std::exception &) {
  2762. res_error(res, format_error_response("Invalid slot ID", ERROR_TYPE_INVALID_REQUEST));
  2763. return;
  2764. }
  2765. std::string action = req.get_param_value("action");
  2766. if (action == "save") {
  2767. handle_slots_save(req, res, id_slot);
  2768. } else if (action == "restore") {
  2769. handle_slots_restore(req, res, id_slot);
  2770. } else if (action == "erase") {
  2771. handle_slots_erase(req, res, id_slot);
  2772. } else {
  2773. res_error(res, format_error_response("Invalid action", ERROR_TYPE_INVALID_REQUEST));
  2774. }
  2775. };
  2776. const auto handle_props = [&ctx_server, &res_ok](const httplib::Request &, httplib::Response & res) {
  2777. json data = {
  2778. { "default_generation_settings", ctx_server.default_generation_settings_for_props },
  2779. { "total_slots", ctx_server.params_base.n_parallel },
  2780. { "chat_template", llama_get_chat_template(ctx_server.model) },
  2781. };
  2782. res_ok(res, data);
  2783. };
  2784. const auto handle_props_change = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2785. if (!ctx_server.params_base.endpoint_props) {
  2786. res_error(res, format_error_response("This server does not support changing global properties. Start it with `--props`", ERROR_TYPE_NOT_SUPPORTED));
  2787. return;
  2788. }
  2789. json data = json::parse(req.body);
  2790. // update any props here
  2791. res_ok(res, {{ "success", true }});
  2792. };
  2793. // handle completion-like requests (completion, chat, infill)
  2794. // we can optionally provide a custom format for partial results and final results
  2795. const auto handle_completions_generic = [&ctx_server, &res_error, &res_ok](
  2796. server_task_inf_type inf_type,
  2797. json & data,
  2798. httplib::Response & res,
  2799. bool oai_compat = false) {
  2800. if (ctx_server.params_base.embedding) {
  2801. res_error(res, format_error_response("This server does not support completions. Start it without `--embeddings`", ERROR_TYPE_NOT_SUPPORTED));
  2802. return;
  2803. }
  2804. data["completion_id"] = gen_chatcmplid();
  2805. std::vector<server_task> tasks = ctx_server.create_tasks_inference(data, inf_type);
  2806. ctx_server.queue_results.add_waiting_tasks(tasks);
  2807. ctx_server.queue_tasks.post(tasks);
  2808. bool stream = json_value(data, "stream", false);
  2809. const auto task_ids = server_task::get_list_id(tasks);
  2810. if (!stream) {
  2811. ctx_server.receive_multi_results(task_ids, [&](std::vector<server_task_result_ptr> & results) {
  2812. if (results.size() == 1) {
  2813. // single result
  2814. res_ok(res, results[0]->to_json());
  2815. } else {
  2816. // multiple results (multitask)
  2817. json arr = json::array();
  2818. for (auto & res : results) {
  2819. arr.push_back(res->to_json());
  2820. }
  2821. res_ok(res, arr);
  2822. }
  2823. }, [&](const json & error_data) {
  2824. res_error(res, error_data);
  2825. });
  2826. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  2827. } else {
  2828. const auto chunked_content_provider = [task_ids, &ctx_server, oai_compat](size_t, httplib::DataSink & sink) {
  2829. ctx_server.receive_cmpl_results_stream(task_ids, [&](server_task_result_ptr & result) -> bool {
  2830. json res_json = result->to_json();
  2831. if (res_json.is_array()) {
  2832. for (const auto & res : res_json) {
  2833. if (!server_sent_event(sink, "data", res)) {
  2834. return false;
  2835. }
  2836. }
  2837. return true;
  2838. } else {
  2839. return server_sent_event(sink, "data", res_json);
  2840. }
  2841. }, [&](const json & error_data) {
  2842. server_sent_event(sink, "error", error_data);
  2843. });
  2844. if (oai_compat) {
  2845. static const std::string ev_done = "data: [DONE]\n\n";
  2846. sink.write(ev_done.data(), ev_done.size());
  2847. }
  2848. sink.done();
  2849. return false;
  2850. };
  2851. auto on_complete = [task_ids, &ctx_server] (bool) {
  2852. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  2853. };
  2854. res.set_chunked_content_provider("text/event-stream", chunked_content_provider, on_complete);
  2855. }
  2856. };
  2857. const auto handle_completions = [&handle_completions_generic](const httplib::Request & req, httplib::Response & res) {
  2858. json data = json::parse(req.body);
  2859. return handle_completions_generic(SERVER_TASK_INF_TYPE_COMPLETION, data, res);
  2860. };
  2861. const auto handle_infill = [&ctx_server, &res_error, &handle_completions_generic](const httplib::Request & req, httplib::Response & res) {
  2862. // check model compatibility
  2863. std::string err;
  2864. if (llama_token_fim_pre(ctx_server.model) == LLAMA_TOKEN_NULL) {
  2865. err += "prefix token is missing. ";
  2866. }
  2867. if (llama_token_fim_suf(ctx_server.model) == LLAMA_TOKEN_NULL) {
  2868. err += "suffix token is missing. ";
  2869. }
  2870. if (llama_token_fim_mid(ctx_server.model) == LLAMA_TOKEN_NULL) {
  2871. err += "middle token is missing. ";
  2872. }
  2873. if (!err.empty()) {
  2874. res_error(res, format_error_response(string_format("Infill is not supported by this model: %s", err.c_str()), ERROR_TYPE_NOT_SUPPORTED));
  2875. return;
  2876. }
  2877. json data = json::parse(req.body);
  2878. // validate input
  2879. if (!data.contains("input_prefix")) {
  2880. res_error(res, format_error_response("\"input_prefix\" is required", ERROR_TYPE_INVALID_REQUEST));
  2881. }
  2882. if (!data.contains("input_suffix")) {
  2883. res_error(res, format_error_response("\"input_suffix\" is required", ERROR_TYPE_INVALID_REQUEST));
  2884. }
  2885. if (data.contains("input_extra") && !data.at("input_extra").is_array()) {
  2886. res_error(res, format_error_response("\"input_extra\" must be an array of {\"filename\": string, \"text\": string}", ERROR_TYPE_INVALID_REQUEST));
  2887. return;
  2888. }
  2889. json input_extra = json_value(data, "input_extra", json::array());
  2890. for (const auto & chunk : input_extra) {
  2891. // { "text": string, "filename": string }
  2892. if (!chunk.contains("text") || !chunk.at("text").is_string()) {
  2893. res_error(res, format_error_response("extra_context chunk must contain a \"text\" field with a string value", ERROR_TYPE_INVALID_REQUEST));
  2894. return;
  2895. }
  2896. // filename is optional
  2897. if (chunk.contains("filename") && !chunk.at("filename").is_string()) {
  2898. res_error(res, format_error_response("extra_context chunk's \"filename\" field must be a string", ERROR_TYPE_INVALID_REQUEST));
  2899. return;
  2900. }
  2901. }
  2902. data["input_extra"] = input_extra; // default to empty array if it's not exist
  2903. return handle_completions_generic(SERVER_TASK_INF_TYPE_INFILL, data, res);
  2904. };
  2905. const auto handle_chat_completions = [&ctx_server, &params, &res_error, &handle_completions_generic](const httplib::Request & req, httplib::Response & res) {
  2906. if (ctx_server.params_base.embedding) {
  2907. res_error(res, format_error_response("This server does not support completions. Start it without `--embeddings`", ERROR_TYPE_NOT_SUPPORTED));
  2908. return;
  2909. }
  2910. json data = oaicompat_completion_params_parse(ctx_server.model, json::parse(req.body), params.chat_template);
  2911. data["__oaicompat_chat"] = true;
  2912. return handle_completions_generic(SERVER_TASK_INF_TYPE_COMPLETION, data, res, true);
  2913. };
  2914. const auto handle_models = [&params, &ctx_server](const httplib::Request &, httplib::Response & res) {
  2915. json models = {
  2916. {"object", "list"},
  2917. {"data", {
  2918. {
  2919. {"id", params.model_alias},
  2920. {"object", "model"},
  2921. {"created", std::time(0)},
  2922. {"owned_by", "llamacpp"},
  2923. {"meta", ctx_server.model_meta()}
  2924. },
  2925. }}
  2926. };
  2927. res.set_content(models.dump(), MIMETYPE_JSON);
  2928. };
  2929. const auto handle_tokenize = [&ctx_server, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2930. const json body = json::parse(req.body);
  2931. json tokens_response = json::array();
  2932. if (body.count("content") != 0) {
  2933. const bool add_special = json_value(body, "add_special", false);
  2934. const bool with_pieces = json_value(body, "with_pieces", false);
  2935. llama_tokens tokens = tokenize_mixed(ctx_server.ctx, body.at("content"), add_special, true);
  2936. if (with_pieces) {
  2937. for (const auto& token : tokens) {
  2938. std::string piece = common_token_to_piece(ctx_server.ctx, token);
  2939. json piece_json;
  2940. // Check if the piece is valid UTF-8
  2941. if (is_valid_utf8(piece)) {
  2942. piece_json = piece;
  2943. } else {
  2944. // If not valid UTF-8, store as array of byte values
  2945. piece_json = json::array();
  2946. for (unsigned char c : piece) {
  2947. piece_json.push_back(static_cast<int>(c));
  2948. }
  2949. }
  2950. tokens_response.push_back({
  2951. {"id", token},
  2952. {"piece", piece_json}
  2953. });
  2954. }
  2955. } else {
  2956. tokens_response = tokens;
  2957. }
  2958. }
  2959. const json data = format_tokenizer_response(tokens_response);
  2960. res_ok(res, data);
  2961. };
  2962. const auto handle_detokenize = [&ctx_server, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2963. const json body = json::parse(req.body);
  2964. std::string content;
  2965. if (body.count("tokens") != 0) {
  2966. const llama_tokens tokens = body.at("tokens");
  2967. content = tokens_to_str(ctx_server.ctx, tokens.cbegin(), tokens.cend());
  2968. }
  2969. const json data = format_detokenized_response(content);
  2970. res_ok(res, data);
  2971. };
  2972. const auto handle_embeddings = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  2973. const json body = json::parse(req.body);
  2974. bool oaicompat = false;
  2975. // an input prompt can be a string or a list of tokens (integer)
  2976. json prompt;
  2977. if (body.count("input") != 0) {
  2978. oaicompat = true;
  2979. prompt = body.at("input");
  2980. } else if (body.count("content") != 0) {
  2981. // with "content", we only support single prompt
  2982. prompt = std::vector<std::string>{body.at("content")};
  2983. } else {
  2984. res_error(res, format_error_response("\"input\" or \"content\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  2985. return;
  2986. }
  2987. // create and queue the task
  2988. json responses = json::array();
  2989. bool error = false;
  2990. {
  2991. std::vector<server_task> tasks = ctx_server.create_tasks_inference({{"prompt", prompt}}, SERVER_TASK_INF_TYPE_EMBEDDING);
  2992. ctx_server.queue_results.add_waiting_tasks(tasks);
  2993. ctx_server.queue_tasks.post(tasks);
  2994. // get the result
  2995. std::unordered_set<int> task_ids = server_task::get_list_id(tasks);
  2996. ctx_server.receive_multi_results(task_ids, [&](std::vector<server_task_result_ptr> & results) {
  2997. for (auto & res : results) {
  2998. GGML_ASSERT(dynamic_cast<server_task_result_embd*>(res.get()) != nullptr);
  2999. responses.push_back(res->to_json());
  3000. }
  3001. }, [&](const json & error_data) {
  3002. res_error(res, error_data);
  3003. error = true;
  3004. });
  3005. ctx_server.queue_results.remove_waiting_task_ids(task_ids);
  3006. }
  3007. if (error) {
  3008. return;
  3009. }
  3010. // write JSON response
  3011. json root = oaicompat
  3012. ? format_embeddings_response_oaicompat(body, responses)
  3013. : responses[0];
  3014. res_ok(res, root);
  3015. };
  3016. const auto handle_rerank = [&ctx_server, &res_error, &res_ok](const httplib::Request & req, httplib::Response & res) {
  3017. if (!ctx_server.params_base.reranking || ctx_server.params_base.embedding) {
  3018. res_error(res, format_error_response("This server does not support reranking. Start it with `--reranking` and without `--embedding`", ERROR_TYPE_NOT_SUPPORTED));
  3019. return;
  3020. }
  3021. const json body = json::parse(req.body);
  3022. // TODO: implement
  3023. //int top_n = 1;
  3024. //if (body.count("top_n") != 1) {
  3025. // top_n = body.at("top_n");
  3026. //} else {
  3027. // res_error(res, format_error_response("\"top_n\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  3028. // return;
  3029. //}
  3030. json query;
  3031. if (body.count("query") == 1) {
  3032. query = body.at("query");
  3033. if (!query.is_string()) {
  3034. res_error(res, format_error_response("\"query\" must be a string", ERROR_TYPE_INVALID_REQUEST));
  3035. return;
  3036. }
  3037. } else {
  3038. res_error(res, format_error_response("\"query\" must be provided", ERROR_TYPE_INVALID_REQUEST));
  3039. return;
  3040. }
  3041. std::vector<std::string> documents = json_value(body, "documents", std::vector<std::string>());
  3042. if (documents.empty()) {
  3043. res_error(res, format_error_response("\"documents\" must be a non-empty string array", ERROR_TYPE_INVALID_REQUEST));
  3044. return;
  3045. }
  3046. // construct prompt object: array of ["query", "doc0", "doc1", ...]
  3047. json prompt;
  3048. prompt.push_back(query);
  3049. for (const auto & doc : documents) {
  3050. prompt.push_back(doc);
  3051. }
  3052. LOG_DBG("rerank prompt: %s\n", prompt.dump().c_str());
  3053. // create and queue the task
  3054. json responses = json::array();
  3055. bool error = false;
  3056. {
  3057. std::vector<server_task> tasks = ctx_server.create_tasks_inference({{"prompt", prompt}}, SERVER_TASK_INF_TYPE_RERANK);
  3058. ctx_server.queue_results.add_waiting_tasks(tasks);
  3059. ctx_server.queue_tasks.post(tasks);
  3060. // get the result
  3061. std::unordered_set<int> task_ids = server_task::get_list_id(tasks);
  3062. ctx_server.receive_multi_results(task_ids, [&](std::vector<server_task_result_ptr> & results) {
  3063. for (auto & res : results) {
  3064. GGML_ASSERT(dynamic_cast<server_task_result_rerank*>(res.get()) != nullptr);
  3065. responses.push_back(res->to_json());
  3066. }
  3067. }, [&](const json & error_data) {
  3068. res_error(res, error_data);
  3069. error = true;
  3070. });
  3071. }
  3072. if (error) {
  3073. return;
  3074. }
  3075. // write JSON response
  3076. json root = format_response_rerank(body, responses);
  3077. res_ok(res, root);
  3078. };
  3079. const auto handle_lora_adapters_list = [&](const httplib::Request &, httplib::Response & res) {
  3080. json result = json::array();
  3081. for (size_t i = 0; i < ctx_server.loras.size(); ++i) {
  3082. auto & lora = ctx_server.loras[i];
  3083. result.push_back({
  3084. {"id", i},
  3085. {"path", lora.path},
  3086. {"scale", lora.scale},
  3087. });
  3088. }
  3089. res_ok(res, result);
  3090. res.status = 200; // HTTP OK
  3091. };
  3092. const auto handle_lora_adapters_apply = [&](const httplib::Request & req, httplib::Response & res) {
  3093. const std::vector<json> body = json::parse(req.body);
  3094. int max_idx = ctx_server.loras.size();
  3095. // clear existing value
  3096. for (auto & lora : ctx_server.loras) {
  3097. lora.scale = 0.0f;
  3098. }
  3099. // set value
  3100. for (auto entry : body) {
  3101. int id = entry.at("id");
  3102. float scale = entry.at("scale");
  3103. if (0 <= id && id < max_idx) {
  3104. ctx_server.loras[id].scale = scale;
  3105. } else {
  3106. throw std::runtime_error("invalid adapter id");
  3107. }
  3108. }
  3109. server_task task;
  3110. task.type = SERVER_TASK_TYPE_SET_LORA;
  3111. const int id_task = ctx_server.queue_tasks.post(task);
  3112. ctx_server.queue_results.add_waiting_task_id(id_task);
  3113. server_task_result_ptr result = ctx_server.queue_results.recv(id_task);
  3114. ctx_server.queue_results.remove_waiting_task_id(id_task);
  3115. if (result->is_error()) {
  3116. res_error(res, result->to_json());
  3117. return;
  3118. }
  3119. GGML_ASSERT(dynamic_cast<server_task_result_apply_lora*>(result.get()) != nullptr);
  3120. res_ok(res, result->to_json());
  3121. };
  3122. //
  3123. // Router
  3124. //
  3125. // register static assets routes
  3126. if (!params.public_path.empty()) {
  3127. // Set the base directory for serving static files
  3128. bool is_found = svr->set_mount_point("/", params.public_path);
  3129. if (!is_found) {
  3130. LOG_ERR("%s: static assets path not found: %s\n", __func__, params.public_path.c_str());
  3131. return 1;
  3132. }
  3133. } else {
  3134. // using embedded static index.html
  3135. svr->Get("/", [](const httplib::Request &, httplib::Response & res) {
  3136. res.set_content(reinterpret_cast<const char*>(index_html), index_html_len, "text/html; charset=utf-8");
  3137. return false;
  3138. });
  3139. }
  3140. // register API routes
  3141. svr->Get ("/health", handle_health); // public endpoint (no API key check)
  3142. svr->Get ("/metrics", handle_metrics);
  3143. svr->Get ("/props", handle_props);
  3144. svr->Post("/props", handle_props_change);
  3145. svr->Get ("/models", handle_models); // public endpoint (no API key check)
  3146. svr->Get ("/v1/models", handle_models); // public endpoint (no API key check)
  3147. svr->Post("/completion", handle_completions); // legacy
  3148. svr->Post("/completions", handle_completions);
  3149. svr->Post("/v1/completions", handle_completions);
  3150. svr->Post("/chat/completions", handle_chat_completions);
  3151. svr->Post("/v1/chat/completions", handle_chat_completions);
  3152. svr->Post("/infill", handle_infill);
  3153. svr->Post("/embedding", handle_embeddings); // legacy
  3154. svr->Post("/embeddings", handle_embeddings);
  3155. svr->Post("/v1/embeddings", handle_embeddings);
  3156. svr->Post("/rerank", handle_rerank);
  3157. svr->Post("/reranking", handle_rerank);
  3158. svr->Post("/v1/rerank", handle_rerank);
  3159. svr->Post("/v1/reranking", handle_rerank);
  3160. svr->Post("/tokenize", handle_tokenize);
  3161. svr->Post("/detokenize", handle_detokenize);
  3162. // LoRA adapters hotswap
  3163. svr->Get ("/lora-adapters", handle_lora_adapters_list);
  3164. svr->Post("/lora-adapters", handle_lora_adapters_apply);
  3165. // Save & load slots
  3166. svr->Get ("/slots", handle_slots);
  3167. svr->Post("/slots/:id_slot", handle_slots_action);
  3168. //
  3169. // Start the server
  3170. //
  3171. if (params.n_threads_http < 1) {
  3172. // +2 threads for monitoring endpoints
  3173. params.n_threads_http = std::max(params.n_parallel + 2, (int32_t) std::thread::hardware_concurrency() - 1);
  3174. }
  3175. log_data["n_threads_http"] = std::to_string(params.n_threads_http);
  3176. svr->new_task_queue = [&params] { return new httplib::ThreadPool(params.n_threads_http); };
  3177. // clean up function, to be called before exit
  3178. auto clean_up = [&svr]() {
  3179. svr->stop();
  3180. llama_backend_free();
  3181. };
  3182. // bind HTTP listen port
  3183. bool was_bound = false;
  3184. if (params.port == 0) {
  3185. int bound_port = svr->bind_to_any_port(params.hostname);
  3186. if ((was_bound = (bound_port >= 0))) {
  3187. params.port = bound_port;
  3188. }
  3189. } else {
  3190. was_bound = svr->bind_to_port(params.hostname, params.port);
  3191. }
  3192. if (!was_bound) {
  3193. //LOG_ERROR("couldn't bind HTTP server socket", {
  3194. // {"hostname", params.hostname},
  3195. // {"port", params.port},
  3196. //});
  3197. LOG_ERR("%s: couldn't bind HTTP server socket, hostname: %s, port: %d\n", __func__, params.hostname.c_str(), params.port);
  3198. clean_up();
  3199. return 1;
  3200. }
  3201. // run the HTTP server in a thread
  3202. std::thread t([&]() { svr->listen_after_bind(); });
  3203. svr->wait_until_ready();
  3204. LOG_INF("%s: HTTP server is listening, hostname: %s, port: %d, http threads: %d\n", __func__, params.hostname.c_str(), params.port, params.n_threads_http);
  3205. // load the model
  3206. LOG_INF("%s: loading model\n", __func__);
  3207. if (!ctx_server.load_model(params)) {
  3208. clean_up();
  3209. t.join();
  3210. LOG_ERR("%s: exiting due to model loading error\n", __func__);
  3211. return 1;
  3212. }
  3213. ctx_server.init();
  3214. state.store(SERVER_STATE_READY);
  3215. LOG_INF("%s: model loaded\n", __func__);
  3216. // if a custom chat template is not supplied, we will use the one that comes with the model (if any)
  3217. if (params.chat_template.empty()) {
  3218. if (!ctx_server.validate_model_chat_template()) {
  3219. LOG_WRN("%s: The chat template that comes with this model is not yet supported, falling back to chatml. This may cause the model to output suboptimal responses\n", __func__);
  3220. params.chat_template = "chatml";
  3221. }
  3222. }
  3223. // print sample chat example to make it clear which template is used
  3224. LOG_INF("%s: chat template, built_in: %d, chat_example: '%s'\n", __func__, params.chat_template.empty(), common_chat_format_example(ctx_server.model, params.chat_template).c_str());
  3225. ctx_server.queue_tasks.on_new_task(std::bind(
  3226. &server_context::process_single_task, &ctx_server, std::placeholders::_1));
  3227. ctx_server.queue_tasks.on_update_slots(std::bind(
  3228. &server_context::update_slots, &ctx_server));
  3229. shutdown_handler = [&](int) {
  3230. ctx_server.queue_tasks.terminate();
  3231. };
  3232. LOG_INF("%s: server is listening on http://%s:%d - starting the main loop\n", __func__, params.hostname.c_str(), params.port);
  3233. ctx_server.queue_tasks.start_loop();
  3234. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  3235. struct sigaction sigint_action;
  3236. sigint_action.sa_handler = signal_handler;
  3237. sigemptyset (&sigint_action.sa_mask);
  3238. sigint_action.sa_flags = 0;
  3239. sigaction(SIGINT, &sigint_action, NULL);
  3240. sigaction(SIGTERM, &sigint_action, NULL);
  3241. #elif defined (_WIN32)
  3242. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  3243. return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
  3244. };
  3245. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  3246. #endif
  3247. clean_up();
  3248. t.join();
  3249. return 0;
  3250. }