llama-context.cpp 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642
  1. #include "llama-context.h"
  2. #include "llama-arch.h"
  3. #include "llama-impl.h"
  4. #include "llama-batch.h"
  5. #include "llama-io.h"
  6. #include "llama-memory.h"
  7. #include "llama-mmap.h"
  8. #include "llama-model.h"
  9. #include <cinttypes>
  10. #include <cmath>
  11. #include <cstring>
  12. #include <limits>
  13. #include <stdexcept>
  14. //
  15. // llama_context
  16. //
  17. llama_context::llama_context(
  18. const llama_model & model,
  19. llama_context_params params) :
  20. model(model),
  21. balloc(std::make_unique<llama_batch_allocr>(model.hparams.n_pos_per_embd())) {
  22. // TODO warning when creating llama_context with awkward ctx size that is not a power of 2,
  23. // may need to be backend-dependent
  24. LLAMA_LOG_INFO("%s: constructing llama_context\n", __func__);
  25. t_start_us = model.t_start_us;
  26. t_load_us = model.t_load_us;
  27. const auto & hparams = model.hparams;
  28. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  29. if (cparams.n_seq_max > LLAMA_MAX_SEQ) {
  30. throw std::runtime_error("n_seq_max must be <= " + std::to_string(LLAMA_MAX_SEQ));
  31. }
  32. cparams.n_threads = params.n_threads;
  33. cparams.n_threads_batch = params.n_threads_batch;
  34. cparams.yarn_ext_factor = params.yarn_ext_factor >= 0.0f ? params.yarn_ext_factor : hparams.yarn_ext_factor;
  35. cparams.yarn_attn_factor = params.yarn_attn_factor >= 0.0f ? params.yarn_attn_factor : hparams.yarn_attn_factor;
  36. cparams.yarn_beta_fast = params.yarn_beta_fast >= 0.0f ? params.yarn_beta_fast : hparams.yarn_beta_fast;
  37. cparams.yarn_beta_slow = params.yarn_beta_slow >= 0.0f ? params.yarn_beta_slow : hparams.yarn_beta_slow;
  38. cparams.embeddings = params.embeddings;
  39. cparams.offload_kqv = params.offload_kqv;
  40. cparams.no_perf = params.no_perf;
  41. cparams.pooling_type = params.pooling_type;
  42. cparams.warmup = false;
  43. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  44. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  45. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  46. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  47. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  48. hparams.n_ctx_train;
  49. cparams.cb_eval = params.cb_eval;
  50. cparams.cb_eval_user_data = params.cb_eval_user_data;
  51. // Initialize backend samplers here so they are part of the sampling graph
  52. // before the reserve passes run later in this function. This avoids a later
  53. // re-reserve when graph nodes change.
  54. if (params.samplers != nullptr && params.n_samplers > 0) {
  55. for (size_t i = 0; i < params.n_samplers; ++i) {
  56. const auto & config = params.samplers[i];
  57. if (llama_sampler_chain_get(config.sampler, -1) == nullptr) {
  58. throw std::runtime_error("the backend samplers must be of type llama_sampler_chain");
  59. }
  60. if (set_sampler(config.seq_id, config.sampler)) {
  61. const int n_samplers = llama_sampler_chain_n(config.sampler);
  62. LLAMA_LOG_INFO("%s: setting backend sampler for seq_id %d (n = %d)\n", __func__, config.seq_id, n_samplers);
  63. }
  64. }
  65. }
  66. auto rope_scaling_type = params.rope_scaling_type;
  67. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  68. rope_scaling_type = hparams.rope_scaling_type_train;
  69. }
  70. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  71. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  72. }
  73. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  74. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  75. }
  76. if (cparams.yarn_ext_factor != 0) {
  77. static auto get_mscale = [](float scale, float mscale) {
  78. return scale <= 1.0f ? 1.0f : (0.1f * mscale * logf(scale) + 1.0f);
  79. };
  80. const float factor = 1.0f / cparams.rope_freq_scale;
  81. // ref: https://github.com/huggingface/transformers/blob/6d00f6b0a5679c36510f203e4226e36f517c3032/src/transformers/modeling_rope_utils.py#L336-L348
  82. if (hparams.rope_yarn_log_mul != 0.0f) {
  83. // note: here we assume `mscale == 1.0f`
  84. // TODO: start reading the actual value of mscale and handle the case where it is not 1.0f
  85. float mscale = 1.0f;
  86. const float mscale_all_dims = hparams.rope_yarn_log_mul;
  87. // [TAG_DEEPSEEK2_YARN_LOG_MUL_FIX]
  88. // special-case DEEPSEEK v2:
  89. // https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite-Chat/blob/main/config.json#L42-L43
  90. if (model.arch == LLM_ARCH_DEEPSEEK2 && mscale_all_dims != 1.0f) {
  91. mscale = mscale_all_dims;
  92. }
  93. cparams.yarn_attn_factor = get_mscale(factor, mscale) / get_mscale(factor, mscale_all_dims);
  94. LLAMA_LOG_WARN("%s: setting new yarn_attn_factor = %.4f (mscale == %.1f, mscale_all_dim = %.1f)\n",
  95. __func__, cparams.yarn_attn_factor, mscale, mscale_all_dims);
  96. } else {
  97. cparams.yarn_attn_factor = get_mscale(factor, 1.0f);
  98. }
  99. // when YARN is applied with yarn_ext_factor != 0.0f, we need to cancel this factor:
  100. // https://github.com/ggml-org/llama.cpp/blob/a81a569577cc38b32558958b048228150be63eae/ggml/src/ggml-cpu/ops.cpp#L5541-L5544
  101. //
  102. // ref: https://github.com/ggml-org/llama.cpp/discussions/7416
  103. // https://github.com/ggml-org/llama.cpp/pull/17945
  104. cparams.yarn_attn_factor *= 1.0f / (1.0f + 0.1f * logf(factor));
  105. }
  106. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  107. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  108. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  109. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  110. } else {
  111. cparams.pooling_type = hparams.pooling_type;
  112. }
  113. }
  114. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  115. cparams.causal_attn = hparams.causal_attn;
  116. } else {
  117. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  118. }
  119. cparams.flash_attn = params.flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED;
  120. // with causal attention, the batch size is limited by the context size
  121. cparams.n_batch = cparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  122. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  123. cparams.op_offload = params.op_offload;
  124. cparams.kv_unified = params.kv_unified;
  125. {
  126. const char * LLAMA_GRAPH_REUSE_DISABLE = getenv("LLAMA_GRAPH_REUSE_DISABLE");
  127. graph_reuse_disable = LLAMA_GRAPH_REUSE_DISABLE ? (atoi(LLAMA_GRAPH_REUSE_DISABLE) != 0) : graph_reuse_disable;
  128. if (graph_reuse_disable) {
  129. LLAMA_LOG_WARN("%s: graph reuse disabled\n", __func__);
  130. }
  131. }
  132. // ref: https://github.com/ggml-org/llama.cpp/pull/17046#discussion_r2503085732
  133. cparams.n_ctx = GGML_PAD(cparams.n_ctx, 256);
  134. if (cparams.kv_unified) {
  135. cparams.n_ctx_seq = cparams.n_ctx;
  136. } else {
  137. cparams.n_ctx_seq = cparams.n_ctx / cparams.n_seq_max;
  138. cparams.n_ctx_seq = GGML_PAD(cparams.n_ctx_seq, 256);
  139. if (cparams.n_ctx_seq == 0) {
  140. throw std::runtime_error("n_ctx_seq == 0");
  141. }
  142. if (cparams.n_ctx != cparams.n_ctx_seq * cparams.n_seq_max) {
  143. cparams.n_ctx = cparams.n_ctx_seq * cparams.n_seq_max;
  144. LLAMA_LOG_WARN("%s: n_ctx is not divisible by n_seq_max - rounding down to %u\n", __func__, cparams.n_ctx);
  145. }
  146. }
  147. LLAMA_LOG_INFO("%s: n_seq_max = %u\n", __func__, cparams.n_seq_max);
  148. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  149. LLAMA_LOG_INFO("%s: n_ctx_seq = %u\n", __func__, cparams.n_ctx_seq);
  150. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  151. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  152. LLAMA_LOG_INFO("%s: causal_attn = %d\n", __func__, cparams.causal_attn);
  153. LLAMA_LOG_INFO("%s: flash_attn = %s\n", __func__, llama_flash_attn_type_name(params.flash_attn_type));
  154. LLAMA_LOG_INFO("%s: kv_unified = %s\n", __func__, cparams.kv_unified ? "true" : "false");
  155. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  156. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  157. if (cparams.n_ctx_seq < hparams.n_ctx_train) {
  158. LLAMA_LOG_WARN("%s: n_ctx_seq (%u) < n_ctx_train (%u) -- the full capacity of the model will not be utilized\n",
  159. __func__, cparams.n_ctx_seq, hparams.n_ctx_train);
  160. }
  161. if (cparams.n_ctx_seq > hparams.n_ctx_train) {
  162. LLAMA_LOG_WARN("%s: n_ctx_seq (%u) > n_ctx_train (%u) -- possible training context overflow\n",
  163. __func__, cparams.n_ctx_seq, hparams.n_ctx_train);
  164. }
  165. if (!hparams.vocab_only) {
  166. // GPU backends
  167. for (auto * dev : model.devices) {
  168. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  169. if (backend == nullptr) {
  170. throw std::runtime_error(format("failed to initialize %s backend", ggml_backend_dev_name(dev)));
  171. }
  172. backends.emplace_back(backend);
  173. }
  174. // add ACCEL backends (such as BLAS)
  175. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  176. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  177. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
  178. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  179. if (backend == nullptr) {
  180. throw std::runtime_error(format("failed to initialize %s backend", ggml_backend_dev_name(dev)));
  181. }
  182. backends.emplace_back(backend);
  183. }
  184. }
  185. // add CPU backend
  186. backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
  187. if (backend_cpu == nullptr) {
  188. throw std::runtime_error("failed to initialize CPU backend");
  189. }
  190. backends.emplace_back(backend_cpu);
  191. // create a list of the set_n_threads functions in the backends
  192. for (auto & backend : backends) {
  193. ggml_backend_dev_t dev = ggml_backend_get_device(backend.get());
  194. ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
  195. if (reg) {
  196. auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
  197. if (ggml_backend_set_n_threads_fn) {
  198. set_n_threads_fns.emplace_back(backend.get(), ggml_backend_set_n_threads_fn);
  199. }
  200. }
  201. }
  202. llama_set_abort_callback(this, params.abort_callback, params.abort_callback_data);
  203. // graph outputs buffer
  204. {
  205. // resized during inference when a batch uses more outputs
  206. // Create a dummy batch for initialization.
  207. llama_batch dummy_batch = {};
  208. dummy_batch.n_tokens = 0;
  209. if (output_reserve(params.n_seq_max, dummy_batch) < params.n_seq_max) {
  210. throw std::runtime_error("failed to reserve initial output buffer");
  211. }
  212. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  213. ggml_backend_buffer_name (buf_output.get()),
  214. ggml_backend_buffer_get_size(buf_output.get()) / 1024.0 / 1024.0);
  215. }
  216. }
  217. // init the memory module
  218. if (!hparams.vocab_only) {
  219. llama_memory_params params_mem = {
  220. /*.type_k =*/ params.type_k,
  221. /*.type_v =*/ params.type_v,
  222. /*.swa_full =*/ params.swa_full,
  223. };
  224. memory.reset(model.create_memory(params_mem, cparams));
  225. }
  226. // init backends
  227. if (!hparams.vocab_only) {
  228. LLAMA_LOG_DEBUG("%s: enumerating backends\n", __func__);
  229. backend_buft.clear();
  230. backend_ptrs.clear();
  231. backend_buf_exp_size.clear();
  232. for (auto & backend : backends) {
  233. auto * buft = ggml_backend_get_default_buffer_type(backend.get());
  234. auto backend_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
  235. if (backend_type == GGML_BACKEND_DEVICE_TYPE_CPU && !model.devices.empty()) {
  236. // use the host buffer of the first device CPU for faster transfer of the intermediate state
  237. auto * dev = model.devices[0];
  238. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  239. if (host_buft) {
  240. buft = host_buft;
  241. }
  242. }
  243. backend_buft.push_back(buft);
  244. backend_ptrs.push_back(backend.get());
  245. backend_buf_exp_size.push_back(0);
  246. }
  247. LLAMA_LOG_DEBUG("%s: backend_ptrs.size() = %zu\n", __func__, backend_ptrs.size());
  248. const uint32_t n_seqs = cparams.n_seq_max;
  249. const uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  250. const size_t max_nodes = this->graph_max_nodes(n_tokens);
  251. LLAMA_LOG_DEBUG("%s: max_nodes = %zu\n", __func__, max_nodes);
  252. gf_res_prev.reset(new llm_graph_result(max_nodes));
  253. gf_res_reserve.reset(new llm_graph_result(max_nodes));
  254. // TODO: move these checks to ggml_backend_sched
  255. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  256. bool pipeline_parallel =
  257. model.n_devices() > 1 &&
  258. model.n_gpu_layers() > model.hparams.n_layer &&
  259. model.split_mode() == LLAMA_SPLIT_MODE_LAYER &&
  260. cparams.offload_kqv &&
  261. !model.has_tensor_overrides();
  262. // pipeline parallelism requires support for async compute and events in all devices
  263. if (pipeline_parallel) {
  264. for (auto & backend : backends) {
  265. auto dev_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
  266. if (dev_type == GGML_BACKEND_DEVICE_TYPE_CPU) {
  267. // ignore CPU backend
  268. continue;
  269. }
  270. auto * dev = ggml_backend_get_device(backend.get());
  271. ggml_backend_dev_props props;
  272. ggml_backend_dev_get_props(dev, &props);
  273. if (!props.caps.async || !props.caps.events) {
  274. // device does not support async compute or events
  275. pipeline_parallel = false;
  276. break;
  277. }
  278. }
  279. }
  280. sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), max_nodes, pipeline_parallel, cparams.op_offload));
  281. if (pipeline_parallel) {
  282. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(sched.get()));
  283. }
  284. llama_memory_context_ptr mctx;
  285. if (memory) {
  286. LLAMA_LOG_DEBUG("%s: reserving full memory module\n", __func__);
  287. mctx = memory->init_full();
  288. if (!mctx) {
  289. throw std::runtime_error("failed to initialize memory module");
  290. }
  291. }
  292. cross.v_embd.clear();
  293. // avoid reserving graphs with zero outputs - assume one output per sequence
  294. n_outputs = n_seqs;
  295. LLAMA_LOG_DEBUG("%s: worst-case: n_tokens = %d, n_seqs = %d, n_outputs = %d\n", __func__, n_tokens, n_seqs, n_outputs);
  296. // resolve automatic Flash Attention use
  297. if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO) {
  298. auto * gf = graph_reserve(1, n_seqs, n_outputs, mctx.get(), true);
  299. if (!gf) {
  300. throw std::runtime_error("failed to split graph for Flash Attention check");
  301. }
  302. const size_t prefix_len = strlen(LLAMA_TENSOR_NAME_FATTN) + 1;
  303. bool fa_device_mismatch = false;
  304. for (int i = 0; i < ggml_graph_n_nodes(gf); i++) {
  305. ggml_tensor * n = ggml_graph_node(gf, i);
  306. if (n->op != GGML_OP_FLASH_ATTN_EXT) {
  307. continue;
  308. }
  309. ggml_backend_dev_t device_fa = ggml_backend_get_device(
  310. ggml_backend_sched_get_tensor_backend(sched.get(), n));
  311. // TODO: instead of the tensor names, use a map to keep track of which (FA) tensors belong to which layer
  312. GGML_ASSERT(strncmp(n->name, LLAMA_TENSOR_NAME_FATTN "-", prefix_len) == 0);
  313. const int il = std::stoi(n->name + prefix_len);
  314. ggml_backend_dev_t device_kv = model.dev_layer(il);
  315. if (device_fa != device_kv) {
  316. LLAMA_LOG_WARN("%s: layer %d is assigned to device %s but the Flash Attention tensor "
  317. "is assigned to device %s (usually due to missing support)\n",
  318. __func__, il, ggml_backend_dev_name(device_kv), ggml_backend_dev_name(device_fa));
  319. // FIXME: fa_device_mismatch logic is wrong for --no-kv-offload, but this is broken anyways
  320. fa_device_mismatch = true;
  321. break;
  322. }
  323. }
  324. if (fa_device_mismatch) {
  325. cparams.flash_attn = false;
  326. LLAMA_LOG_WARN("%s: Flash Attention was auto, set to disabled\n", __func__);
  327. if (ggml_is_quantized(params.type_v)) {
  328. throw std::runtime_error("quantized V cache was requested, but this requires Flash Attention");
  329. }
  330. } else {
  331. cparams.flash_attn = true;
  332. LLAMA_LOG_INFO("%s: Flash Attention was auto, set to enabled\n", __func__);
  333. }
  334. }
  335. // reserve worst-case graph
  336. int n_splits_pp = -1;
  337. int n_nodes_pp = -1;
  338. int n_splits_tg = -1;
  339. int n_nodes_tg = -1;
  340. // reserve pp (prompt processing) graph first so that buffers are only allocated once
  341. {
  342. auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get(),
  343. model.hparams.no_alloc, model.hparams.no_alloc ? backend_buf_exp_size.data() : nullptr);
  344. if (!gf) {
  345. if (pipeline_parallel) {
  346. LLAMA_LOG_WARN("%s: compute buffer allocation failed, retrying without pipeline parallelism\n", __func__);
  347. sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), max_nodes, false, cparams.op_offload));
  348. gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get());
  349. }
  350. if (!gf) {
  351. throw std::runtime_error("failed to allocate compute pp buffers");
  352. }
  353. }
  354. n_splits_pp = ggml_backend_sched_get_n_splits(sched.get());
  355. n_nodes_pp = ggml_graph_n_nodes(gf);
  356. }
  357. // reserve with tg (token generation) graph to get the number of splits and nodes
  358. {
  359. auto * gf = graph_reserve(n_seqs, n_seqs, n_seqs, mctx.get(), model.hparams.no_alloc);
  360. if (!gf) {
  361. throw std::runtime_error("failed to allocate compute tg buffers");
  362. }
  363. n_splits_tg = ggml_backend_sched_get_n_splits(sched.get());
  364. n_nodes_tg = ggml_graph_n_nodes(gf);
  365. }
  366. // reserve again with pp graph to avoid ggml-alloc reallocations during inference
  367. {
  368. // TODO: not sure if the following graph would be worster case for multi-stream KV caches:
  369. //
  370. // auto * gf = graph_reserve(n_tokens, 1, n_tokens, mctx.get());
  371. //
  372. auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get(), model.hparams.no_alloc);
  373. if (!gf) {
  374. throw std::runtime_error("failed to allocate compute pp buffers");
  375. }
  376. }
  377. for (size_t i = 0; i < backend_ptrs.size(); ++i) {
  378. ggml_backend_t backend = backend_ptrs[i];
  379. ggml_backend_buffer_type_t buft = backend_buft[i];
  380. if (!model.hparams.no_alloc) {
  381. backend_buf_exp_size[i] = ggml_backend_sched_get_buffer_size(sched.get(), backend);
  382. }
  383. if (backend_buf_exp_size[i] > 1) {
  384. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  385. ggml_backend_buft_name(buft),
  386. backend_buf_exp_size[i] / 1024.0 / 1024.0);
  387. }
  388. }
  389. if (n_nodes_pp == n_nodes_tg) {
  390. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, n_nodes_pp);
  391. } else {
  392. LLAMA_LOG_INFO("%s: graph nodes = %d (with bs=%d), %d (with bs=1)\n", __func__, n_nodes_pp, n_tokens, n_nodes_tg);
  393. }
  394. if (n_splits_pp == n_splits_tg) {
  395. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits_pp);
  396. } else {
  397. LLAMA_LOG_INFO("%s: graph splits = %d (with bs=%d), %d (with bs=1)\n", __func__, n_splits_pp, n_tokens, n_splits_tg);
  398. }
  399. }
  400. // Initialize the full vocabulary token ids for backend samplers.
  401. {
  402. const int n_vocab = model.vocab.n_tokens();
  403. sampling.token_ids_full_vocab.resize(n_vocab);
  404. for (int i = 0; i < n_vocab; ++i) {
  405. sampling.token_ids_full_vocab[i] = i;
  406. }
  407. }
  408. }
  409. llama_context::~llama_context() {
  410. if (!model.hparams.no_alloc) {
  411. for (size_t i = 0; i < backend_ptrs.size(); ++i) {
  412. ggml_backend_t backend = backend_ptrs[i];
  413. ggml_backend_buffer_type_t buft = backend_buft[i];
  414. const size_t size_exp = backend_buf_exp_size[i];
  415. const size_t size_act = ggml_backend_sched_get_buffer_size(sched.get(), backend);
  416. if (size_exp == size_act) {
  417. LLAMA_LOG_DEBUG("%s: %10s compute buffer size is %8.4f MiB, matches expectation of %8.4f MiB\n",
  418. __func__, ggml_backend_buft_name(buft), size_act / (1024.0*1024.0), size_exp / (1024.0*1024.0));
  419. } else {
  420. LLAMA_LOG_WARN("%s: %10s compute buffer size of %8.4f MiB, does not match expectation of %8.4f MiB\n",
  421. __func__, ggml_backend_buft_name(buft), size_act / (1024.0*1024.0), size_exp / (1024.0*1024.0));
  422. }
  423. }
  424. }
  425. ggml_opt_free(opt_ctx);
  426. }
  427. void llama_context::synchronize() {
  428. ggml_backend_sched_synchronize(sched.get());
  429. // FIXME: if multiple single tokens are evaluated without a synchronization,
  430. // the stats will be added to the prompt evaluation stats
  431. // this should only happen when using batch size 1 to evaluate a batch
  432. // add the evaluation to the stats
  433. if (n_queued_tokens == 1) {
  434. if (!cparams.no_perf) {
  435. t_eval_us += ggml_time_us() - t_compute_start_us;
  436. }
  437. n_eval++;
  438. } else if (n_queued_tokens > 1) {
  439. if (!cparams.no_perf) {
  440. t_p_eval_us += ggml_time_us() - t_compute_start_us;
  441. }
  442. n_p_eval += n_queued_tokens;
  443. }
  444. // get a more accurate load time, upon first eval
  445. if (n_queued_tokens > 0 && !has_evaluated_once) {
  446. t_load_us = ggml_time_us() - t_start_us;
  447. has_evaluated_once = true;
  448. }
  449. n_queued_tokens = 0;
  450. t_compute_start_us = 0;
  451. }
  452. const llama_model & llama_context::get_model() const {
  453. return model;
  454. }
  455. const llama_cparams & llama_context::get_cparams() const {
  456. return cparams;
  457. }
  458. ggml_backend_sched_t llama_context::get_sched() const {
  459. return sched.get();
  460. }
  461. uint32_t llama_context::n_ctx() const {
  462. return cparams.n_ctx;
  463. }
  464. uint32_t llama_context::n_ctx_seq() const {
  465. return cparams.n_ctx_seq;
  466. }
  467. uint32_t llama_context::n_batch() const {
  468. return cparams.n_batch;
  469. }
  470. uint32_t llama_context::n_ubatch() const {
  471. return cparams.n_ubatch;
  472. }
  473. uint32_t llama_context::n_seq_max() const {
  474. return cparams.n_seq_max;
  475. }
  476. uint32_t llama_context::n_threads() const {
  477. return cparams.n_threads;
  478. }
  479. uint32_t llama_context::n_threads_batch() const {
  480. return cparams.n_threads_batch;
  481. }
  482. llama_memory_t llama_context::get_memory() const {
  483. return memory.get();
  484. }
  485. bool llama_context::memory_update(bool optimize) {
  486. if (!memory) {
  487. return false;
  488. }
  489. {
  490. const auto mctx = memory->init_update(this, optimize);
  491. switch (mctx->get_status()) {
  492. case LLAMA_MEMORY_STATUS_SUCCESS:
  493. {
  494. // noop
  495. } break;
  496. case LLAMA_MEMORY_STATUS_NO_UPDATE:
  497. {
  498. // no updates need to be performed
  499. return false;
  500. }
  501. case LLAMA_MEMORY_STATUS_FAILED_PREPARE:
  502. case LLAMA_MEMORY_STATUS_FAILED_COMPUTE:
  503. {
  504. LLAMA_LOG_ERROR("%s: failed to prepare memory update\n", __func__);
  505. return false;
  506. }
  507. }
  508. // reset the previous graph result to make sure that it won't be reused
  509. // TODO: change the mctx->apply() to return information if a graph reserve is needed
  510. // reset the graph result only if the memory module did reset the scheduler
  511. gf_res_prev->reset();
  512. if (!mctx->apply()) {
  513. LLAMA_LOG_ERROR("%s: failed to apply memory update\n", __func__);
  514. }
  515. }
  516. // if the memory module did any computation, we have to reserve a new worst-case graph
  517. {
  518. const auto mctx = memory->init_full();
  519. if (!mctx) {
  520. throw std::runtime_error("failed to initialize memory context");
  521. }
  522. const uint32_t n_seqs = cparams.n_seq_max;
  523. const uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  524. auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get());
  525. if (!gf) {
  526. LLAMA_LOG_ERROR("%s: failed to reserve graph after the memory update\n", __func__);
  527. }
  528. }
  529. return true;
  530. }
  531. enum llama_pooling_type llama_context::pooling_type() const {
  532. return cparams.pooling_type;
  533. }
  534. float * llama_context::get_logits() {
  535. output_reorder();
  536. return logits;
  537. }
  538. int64_t llama_context::output_resolve_row(int32_t i) const {
  539. int64_t j = -1;
  540. // support negative indices (last output row)
  541. if (i < 0) {
  542. j = n_outputs + i;
  543. if (j < 0) {
  544. throw std::runtime_error(format("negative index out of range [0, %d)", n_outputs));
  545. }
  546. } else if ((size_t) i >= output_ids.size()) {
  547. throw std::runtime_error(format("out of range [0, %zu)", output_ids.size()));
  548. } else {
  549. // use output_ids to translate the batch token index into a row number
  550. // that holds this token's data.
  551. j = output_ids[i];
  552. }
  553. if (j < 0) {
  554. // the batch token was not configured to output anything
  555. throw std::runtime_error(format("batch.logits[%d] != true", i));
  556. }
  557. if (j >= n_outputs) {
  558. throw std::runtime_error(format("corrupt output buffer (j=%" PRId64 ", n_outputs=%d)", j, n_outputs));
  559. }
  560. return j;
  561. }
  562. float * llama_context::get_logits_ith(int32_t i) {
  563. int64_t j = -1;
  564. output_reorder();
  565. try {
  566. if (logits == nullptr) {
  567. throw std::runtime_error("no logits");
  568. }
  569. // TODO: use output_resolve_row()
  570. if (i < 0) {
  571. j = n_outputs + i;
  572. if (j < 0) {
  573. throw std::runtime_error(format("negative index out of range [0, %d)", n_outputs));
  574. }
  575. } else if ((size_t) i >= output_ids.size()) {
  576. throw std::runtime_error(format("out of range [0, %zu)", output_ids.size()));
  577. } else {
  578. j = output_ids[i];
  579. }
  580. if (j < 0) {
  581. throw std::runtime_error(format("batch.logits[%d] != true", i));
  582. }
  583. if (j >= n_outputs) {
  584. // This should not happen
  585. throw std::runtime_error(format("corrupt output buffer (j=%" PRId64 ", n_outputs=%d)", j, n_outputs));
  586. }
  587. return logits + j*model.vocab.n_tokens();
  588. } catch (const std::exception & err) {
  589. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  590. #ifndef NDEBUG
  591. GGML_ABORT("fatal error");
  592. #else
  593. return nullptr;
  594. #endif
  595. }
  596. }
  597. float * llama_context::get_embeddings() {
  598. output_reorder();
  599. return embd;
  600. }
  601. llama_token * llama_context::get_sampled_tokens() const{
  602. return sampling.sampled;
  603. }
  604. float * llama_context::get_embeddings_ith(int32_t i) {
  605. int64_t j = -1;
  606. output_reorder();
  607. try {
  608. if (embd == nullptr) {
  609. throw std::runtime_error("no embeddings");
  610. }
  611. // TODO: use output_resolve_row()
  612. if (i < 0) {
  613. j = n_outputs + i;
  614. if (j < 0) {
  615. throw std::runtime_error(format("negative index out of range [0, %d)", n_outputs));
  616. }
  617. } else if ((size_t) i >= output_ids.size()) {
  618. throw std::runtime_error(format("out of range [0, %zu)", output_ids.size()));
  619. } else {
  620. j = output_ids[i];
  621. }
  622. if (j < 0) {
  623. throw std::runtime_error(format("batch.logits[%d] != true", i));
  624. }
  625. if (j >= n_outputs) {
  626. // This should not happen
  627. throw std::runtime_error(format("corrupt output buffer (j=%" PRId64 ", n_outputs=%d)", j, n_outputs));
  628. }
  629. return embd + j*model.hparams.n_embd;
  630. } catch (const std::exception & err) {
  631. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  632. #ifndef NDEBUG
  633. GGML_ABORT("fatal error");
  634. #else
  635. return nullptr;
  636. #endif
  637. }
  638. }
  639. float * llama_context::get_embeddings_seq(llama_seq_id seq_id) {
  640. auto it = embd_seq.find(seq_id);
  641. if (it == embd_seq.end()) {
  642. return nullptr;
  643. }
  644. return it->second.data();
  645. }
  646. llama_token llama_context::get_sampled_token_ith(int32_t idx) {
  647. output_reorder();
  648. if (sampling.sampled == nullptr) {
  649. return LLAMA_TOKEN_NULL;
  650. }
  651. try {
  652. const int64_t row = output_resolve_row(idx);
  653. GGML_ASSERT(row < (int64_t) sampling.sampled_size);
  654. return sampling.sampled[row];
  655. } catch (const std::exception & err) {
  656. LLAMA_LOG_ERROR("%s: invalid backend sampled token id %d, reason: %s\n", __func__, idx, err.what());
  657. return LLAMA_TOKEN_NULL;
  658. }
  659. }
  660. float * llama_context::get_sampled_probs_ith(int32_t idx) {
  661. output_reorder();
  662. if (sampling.probs == nullptr) {
  663. return nullptr;
  664. }
  665. try {
  666. const int64_t row = output_resolve_row(idx);
  667. if ((size_t) row >= sampling.probs_count.size() || sampling.probs_count[row] == 0) {
  668. return nullptr;
  669. }
  670. return sampling.probs + row*model.vocab.n_tokens();
  671. } catch (const std::exception & err) {
  672. LLAMA_LOG_ERROR("%s: invalid backend sampled probs id %d, reason: %s\n", __func__, idx, err.what());
  673. return nullptr;
  674. }
  675. }
  676. float * llama_context::get_sampled_logits_ith(int32_t idx) {
  677. output_reorder();
  678. if (sampling.logits == nullptr) {
  679. return nullptr;
  680. }
  681. try {
  682. const int64_t row = output_resolve_row(idx);
  683. if ((size_t) row >= sampling.logits_count.size() || sampling.logits_count[row] == 0) {
  684. return nullptr;
  685. }
  686. return sampling.logits + row*model.vocab.n_tokens();
  687. } catch (const std::exception & err) {
  688. LLAMA_LOG_ERROR("%s: invalid backend sampled logits id %d, reason: %s\n", __func__, idx, err.what());
  689. return nullptr;
  690. }
  691. }
  692. const llama_token * llama_context::get_sampled_candidates_ith(int32_t idx) {
  693. output_reorder();
  694. try {
  695. const int64_t row = output_resolve_row(idx);
  696. if (sampling.candidates != nullptr &&
  697. (size_t) row < sampling.candidates_count.size() &&
  698. sampling.candidates_count[row] > 0) {
  699. return sampling.candidates + row*model.vocab.n_tokens();
  700. }
  701. } catch (const std::exception & err) {
  702. // fallback to full vocab list
  703. }
  704. return sampling.token_ids_full_vocab.data();
  705. }
  706. size_t llama_context::get_sampled_candidates_count(int32_t idx) {
  707. output_reorder();
  708. if (sampling.candidates == nullptr) {
  709. return 0;
  710. }
  711. try {
  712. const int64_t row = output_resolve_row(idx);
  713. if ((size_t) row >= sampling.candidates_count.size()) {
  714. return 0;
  715. }
  716. return sampling.candidates_count[row];
  717. } catch (const std::exception & err) {
  718. LLAMA_LOG_ERROR("%s: invalid backend sampled candidates count id %d, reason: %s\n", __func__, idx, err.what());
  719. return 0;
  720. }
  721. }
  722. size_t llama_context::get_sampled_logits_count(int32_t idx) {
  723. output_reorder();
  724. if (sampling.logits == nullptr) {
  725. return model.vocab.n_tokens();
  726. }
  727. try {
  728. const int64_t row = output_resolve_row(idx);
  729. if ((size_t) row >= sampling.logits_count.size()) {
  730. return 0;
  731. }
  732. return sampling.logits_count[row];
  733. } catch (const std::exception & err) {
  734. LLAMA_LOG_ERROR("%s: invalid backend sampled logits count id %d, reason: %s\n", __func__, idx, err.what());
  735. return 0;
  736. }
  737. }
  738. size_t llama_context::get_sampled_probs_count(int32_t idx) {
  739. output_reorder();
  740. if (sampling.probs == nullptr) {
  741. return 0;
  742. }
  743. try {
  744. const int64_t row = output_resolve_row(idx);
  745. if ((size_t) row >= sampling.probs_count.size()) {
  746. return 0;
  747. }
  748. return sampling.probs_count[row];
  749. } catch (const std::exception & err) {
  750. LLAMA_LOG_ERROR("%s: invalid backend sampled probs count id %d, reason: %s\n", __func__, idx, err.what());
  751. return 0;
  752. }
  753. }
  754. void llama_context::attach_threadpool(
  755. ggml_threadpool_t threadpool,
  756. ggml_threadpool_t threadpool_batch) {
  757. LLAMA_LOG_DEBUG("%s: call\n", __func__);
  758. this->threadpool = threadpool;
  759. this->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
  760. }
  761. void llama_context::detach_threadpool() {
  762. LLAMA_LOG_DEBUG("%s: call\n", __func__);
  763. this->threadpool = nullptr;
  764. this->threadpool_batch = nullptr;
  765. }
  766. void llama_context::set_n_threads(int32_t n_threads, int32_t n_threads_batch) {
  767. LLAMA_LOG_DEBUG("%s: n_threads = %d, n_threads_batch = %d\n", __func__, n_threads, n_threads_batch);
  768. cparams.n_threads = n_threads;
  769. cparams.n_threads_batch = n_threads_batch;
  770. }
  771. void llama_context::set_abort_callback(bool (*abort_callback)(void * data), void * abort_callback_data) {
  772. LLAMA_LOG_DEBUG("%s: call\n", __func__);
  773. this->abort_callback = abort_callback;
  774. this->abort_callback_data = abort_callback_data;
  775. for (auto & backend : backends) {
  776. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend.get()));
  777. auto * set_abort_callback_fn = (ggml_backend_set_abort_callback_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_abort_callback");
  778. if (set_abort_callback_fn) {
  779. set_abort_callback_fn(backend.get(), this->abort_callback, this->abort_callback_data);
  780. }
  781. }
  782. }
  783. void llama_context::set_embeddings(bool value) {
  784. LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
  785. cparams.embeddings = value;
  786. }
  787. void llama_context::set_causal_attn(bool value) {
  788. LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
  789. cparams.causal_attn = value;
  790. }
  791. void llama_context::set_warmup(bool value) {
  792. LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
  793. cparams.warmup = value;
  794. }
  795. bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) {
  796. LLAMA_LOG_DEBUG("%s: seq_id = %d, sampler = %p\n", __func__, (int) seq_id, (void *) sampler);
  797. const bool can_offload =
  798. sampler &&
  799. sampler->iface->backend_init &&
  800. sampler->iface->backend_apply &&
  801. llama_sampler_chain_n(sampler) > 0;
  802. if (sampler && can_offload) {
  803. ggml_backend_buffer_type_t buft = ggml_backend_dev_buffer_type(model.dev_output());
  804. auto * host_buft = ggml_backend_dev_host_buffer_type(model.dev_output());
  805. if (host_buft) {
  806. buft = host_buft;
  807. }
  808. sampler->iface->backend_init(sampler, buft);
  809. sampling.samplers[seq_id] = sampler;
  810. return true;
  811. }
  812. if (sampler && !can_offload) {
  813. LLAMA_LOG_WARN("%s: sampler '%s' for seq_id = %d, cannot be offloaded to the backend\n", __func__, llama_sampler_name(sampler), seq_id);
  814. sampling.samplers.erase(seq_id);
  815. return false;
  816. }
  817. sampling.samplers.erase(seq_id);
  818. return true;
  819. }
  820. void llama_context::set_adapter_lora(
  821. llama_adapter_lora * adapter,
  822. float scale) {
  823. LLAMA_LOG_DEBUG("%s: adapter = %p, scale = %f\n", __func__, (void *) adapter, scale);
  824. loras[adapter] = scale;
  825. }
  826. bool llama_context::rm_adapter_lora(
  827. llama_adapter_lora * adapter) {
  828. LLAMA_LOG_DEBUG("%s: adapter = %p\n", __func__, (void *) adapter);
  829. auto pos = loras.find(adapter);
  830. if (pos != loras.end()) {
  831. loras.erase(pos);
  832. return true;
  833. }
  834. return false;
  835. }
  836. void llama_context::clear_adapter_lora() {
  837. LLAMA_LOG_DEBUG("%s: call\n", __func__);
  838. loras.clear();
  839. }
  840. bool llama_context::apply_adapter_cvec(
  841. const float * data,
  842. size_t len,
  843. int32_t n_embd,
  844. int32_t il_start,
  845. int32_t il_end) {
  846. LLAMA_LOG_DEBUG("%s: il_start = %d, il_end = %d\n", __func__, il_start, il_end);
  847. return cvec.apply(model, data, len, n_embd, il_start, il_end);
  848. }
  849. llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, llm_graph_type gtype, llama_memory_context_i * mctx, ggml_status & ret) {
  850. if (mctx && !mctx->apply()) {
  851. LLAMA_LOG_ERROR("%s: failed to apply memory context\n", __func__);
  852. ret = GGML_STATUS_FAILED;
  853. return nullptr;
  854. }
  855. auto * res = gf_res_prev.get();
  856. auto * gf = res->get_gf();
  857. // the new graph parameters
  858. // in order to correctly reuse a graph, it's full topology has to be uniquely determined by these parameters
  859. const auto gparams = graph_params(res, ubatch, mctx, gtype);
  860. if (!graph_reuse_disable && res->can_reuse(gparams)) {
  861. //LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__);
  862. n_reused++;
  863. } else {
  864. res->reset();
  865. ggml_backend_sched_reset(sched.get());
  866. ggml_backend_sched_set_eval_callback(sched.get(), cparams.cb_eval, cparams.cb_eval_user_data);
  867. //const auto t_start_us = ggml_time_us();
  868. gf = model.build_graph(gparams);
  869. //LLAMA_LOG_INFO("graph build time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0);
  870. if (!gf) {
  871. LLAMA_LOG_ERROR("%s: failed to initialize graph\n", __func__);
  872. ret = GGML_STATUS_FAILED;
  873. return nullptr;
  874. }
  875. if (!ggml_backend_sched_alloc_graph(sched.get(), gf)) {
  876. LLAMA_LOG_ERROR("%s: failed to allocate graph\n", __func__);
  877. ret = GGML_STATUS_ALLOC_FAILED;
  878. return nullptr;
  879. }
  880. }
  881. // set the input data for the input tensors
  882. {
  883. //const auto t_start_us = ggml_time_us();
  884. res->set_inputs(&ubatch);
  885. //LLAMA_LOG_INFO("graph set inputs time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0);
  886. }
  887. const auto status = graph_compute(res->get_gf(), ubatch.n_tokens > 1);
  888. if (status != GGML_STATUS_SUCCESS) {
  889. LLAMA_LOG_ERROR("%s: failed to compute graph, compute status: %d\n", __func__, status);
  890. ret = status;
  891. return nullptr;
  892. }
  893. ret = GGML_STATUS_SUCCESS;
  894. return res;
  895. }
  896. int llama_context::encode(const llama_batch & batch_inp) {
  897. GGML_ASSERT((!batch_inp.token && batch_inp.embd) || (batch_inp.token && !batch_inp.embd)); // NOLINT
  898. if (batch_inp.n_tokens == 0) {
  899. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  900. return -1;
  901. }
  902. const auto & hparams = model.hparams;
  903. const int64_t n_embd = hparams.n_embd_inp();
  904. const int64_t n_vocab = model.vocab.n_tokens();
  905. // note: during encode, we always pass the full sequence starting from pos = 0
  906. if (!balloc->init(batch_inp, model.vocab, nullptr, n_embd, cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max, true)) {
  907. LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
  908. return -1;
  909. }
  910. const uint32_t n_tokens = balloc->get_n_tokens();
  911. // [TAG_NO_CACHE_PAD]
  912. // TODO: add new split mode where we pad the input sequences so that ubatch.equal_seqs == true
  913. const llama_ubatch ubatch = balloc->split_simple(n_tokens);
  914. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  915. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  916. if (t_compute_start_us == 0) {
  917. t_compute_start_us = ggml_time_us();
  918. }
  919. // TODO: this clear of the buffer can easily be forgotten - need something better
  920. embd_seq.clear();
  921. n_queued_tokens += n_tokens;
  922. // reserve output buffer
  923. if (output_reserve(n_tokens, batch_inp) < n_tokens) {
  924. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  925. return -2;
  926. };
  927. for (uint32_t i = 0; i < n_tokens; ++i) {
  928. output_ids[i] = i;
  929. }
  930. n_outputs = n_tokens;
  931. const auto causal_attn_org = cparams.causal_attn;
  932. // always use non-causal attention for encoder graphs
  933. // TODO: this is a tmp solution until we have a proper way to support enc-dec models
  934. // ref: https://github.com/ggml-org/llama.cpp/pull/12181#issuecomment-2730451223
  935. cparams.causal_attn = false;
  936. ggml_status status;
  937. const auto * res = process_ubatch(ubatch, LLM_GRAPH_TYPE_ENCODER, nullptr, status);
  938. cparams.causal_attn = causal_attn_org;
  939. if (!res) {
  940. switch (status) {
  941. case GGML_STATUS_ABORTED: return 2;
  942. case GGML_STATUS_ALLOC_FAILED: return -2;
  943. case GGML_STATUS_FAILED: return -3;
  944. case GGML_STATUS_SUCCESS: GGML_ABORT("should not happen");
  945. }
  946. }
  947. auto * t_logits = res->get_logits();
  948. auto * t_embd = res->get_embd_pooled() ? res->get_embd_pooled() : res->get_embd();
  949. // extract logits
  950. if (logits && t_logits) {
  951. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits);
  952. GGML_ASSERT(backend_res != nullptr);
  953. GGML_ASSERT(logits != nullptr);
  954. ggml_backend_tensor_get_async(backend_res, t_logits, logits, 0, n_tokens*n_vocab*sizeof(float));
  955. }
  956. // extract embeddings
  957. if (embd && t_embd) {
  958. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd);
  959. GGML_ASSERT(backend_embd != nullptr);
  960. switch (cparams.pooling_type) {
  961. case LLAMA_POOLING_TYPE_NONE:
  962. {
  963. // extract token embeddings
  964. GGML_ASSERT(embd != nullptr);
  965. GGML_ASSERT(n_tokens*n_embd <= (int64_t) embd_size);
  966. ggml_backend_tensor_get_async(backend_embd, t_embd, embd, 0, n_tokens*n_embd*sizeof(float));
  967. } break;
  968. case LLAMA_POOLING_TYPE_MEAN:
  969. case LLAMA_POOLING_TYPE_CLS:
  970. case LLAMA_POOLING_TYPE_LAST:
  971. {
  972. // extract sequence embeddings
  973. auto & embd_seq_out = embd_seq;
  974. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  975. const llama_seq_id seq_id = ubatch.seq_id_unq[s];
  976. const int32_t seq_idx = ubatch.seq_idx[seq_id];
  977. embd_seq_out[seq_id].resize(n_embd);
  978. ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_embd*seq_idx)*sizeof(float), n_embd*sizeof(float));
  979. }
  980. } break;
  981. case LLAMA_POOLING_TYPE_RANK:
  982. {
  983. // extract the rerank score - n_cls_out floats per sequence
  984. auto & embd_seq_out = embd_seq;
  985. const uint32_t n_cls_out = hparams.n_cls_out;
  986. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  987. const llama_seq_id seq_id = ubatch.seq_id_unq[s];
  988. const int32_t seq_idx = ubatch.seq_idx[seq_id];
  989. embd_seq_out[seq_id].resize(n_cls_out);
  990. ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_cls_out*seq_idx)*sizeof(float), n_cls_out*sizeof(float));
  991. }
  992. } break;
  993. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  994. {
  995. GGML_ABORT("unknown pooling type");
  996. }
  997. }
  998. }
  999. // TODO: hacky solution
  1000. if (model.arch == LLM_ARCH_T5 && t_embd) {
  1001. //cross.t_embd = t_embd;
  1002. synchronize();
  1003. cross.n_embd = t_embd->ne[0];
  1004. cross.n_enc = t_embd->ne[1];
  1005. cross.v_embd.resize(cross.n_embd*cross.n_enc);
  1006. memcpy(cross.v_embd.data(), embd, ggml_nbytes(t_embd));
  1007. const auto & batch = balloc->get_batch();
  1008. // remember the sequence ids used during the encoding - needed for cross attention later
  1009. cross.seq_ids_enc.resize(n_tokens);
  1010. for (uint32_t i = 0; i < n_tokens; i++) {
  1011. cross.seq_ids_enc[i].clear();
  1012. for (int s = 0; s < batch.n_seq_id[i]; s++) {
  1013. const llama_seq_id seq_id = batch.seq_id[i][s];
  1014. cross.seq_ids_enc[i].insert(seq_id);
  1015. }
  1016. }
  1017. }
  1018. return 0;
  1019. }
  1020. static std::map<llama_seq_id, uint32_t> build_seq_to_output_row(const llama_ubatch & ubatch, uint32_t row_offset) {
  1021. std::map<llama_seq_id, uint32_t> seq_to_row;
  1022. // how many output tokens we have seen so far for this ubatch.
  1023. uint32_t local = 0;
  1024. for (uint32_t i = 0; i < ubatch.n_tokens; ++i) {
  1025. // skip tokens that are not output.
  1026. if (!ubatch.output[i]) {
  1027. continue;
  1028. }
  1029. const llama_seq_id seq_id = ubatch.seq_id[i][0];
  1030. // row_offset is the number of output tokens before this ubatch.
  1031. seq_to_row[seq_id] = row_offset + local;
  1032. ++local;
  1033. }
  1034. return seq_to_row;
  1035. }
  1036. static void copy_tensor_async_ints(
  1037. const std::map<llama_seq_id, ggml_tensor*> & tensor_map,
  1038. llama_token * sampled,
  1039. size_t sampled_size,
  1040. const std::map<llama_seq_id, uint32_t> & seq_to_row,
  1041. ggml_backend_sched_t sched) {
  1042. if (sampled == nullptr) {
  1043. return;
  1044. }
  1045. for (const auto & [seq_id, tensor] : tensor_map) {
  1046. auto it = seq_to_row.find(seq_id);
  1047. if (it == seq_to_row.end()) {
  1048. continue;
  1049. }
  1050. const uint32_t row = it->second;
  1051. GGML_ASSERT(row < sampled_size);
  1052. GGML_ASSERT(ggml_is_contiguous(tensor) && "sampled tokens tensor must be contiguous for async copy");
  1053. ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched, tensor);
  1054. ggml_backend_tensor_get_async(backend, tensor, sampled + row, 0, sizeof(sampled[row]));
  1055. }
  1056. }
  1057. static void copy_tensor_async_floats(
  1058. const std::map<llama_seq_id, ggml_tensor*> & tensor_map,
  1059. float * dst,
  1060. size_t stride,
  1061. std::vector<uint32_t> & counts,
  1062. const std::map<llama_seq_id, uint32_t> & seq_to_row,
  1063. ggml_backend_sched_t sched) {
  1064. if (dst == nullptr) {
  1065. return;
  1066. }
  1067. for (const auto & [seq_id, tensor] : tensor_map) {
  1068. auto it = seq_to_row.find(seq_id);
  1069. if (it == seq_to_row.end()) {
  1070. continue;
  1071. }
  1072. const uint32_t row = it->second;
  1073. GGML_ASSERT(row < counts.size());
  1074. GGML_ASSERT(ggml_is_contiguous(tensor) && "logits/probs tensor must be contiguous for async copy");
  1075. ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched, tensor);
  1076. float * row_ptr = dst + (size_t) row * stride;
  1077. ggml_backend_tensor_get_async(backend, tensor, row_ptr, 0, ggml_nbytes(tensor));
  1078. // Update the actual number of logits/probabilities that were written for this row.
  1079. counts[row] = ggml_nelements(tensor);
  1080. }
  1081. }
  1082. static void copy_tensor_async_candidates(
  1083. const std::map<llama_seq_id, ggml_tensor*> & tensor_map,
  1084. llama_token * dst,
  1085. size_t stride,
  1086. std::vector<uint32_t> & counts,
  1087. const std::map<llama_seq_id, uint32_t> & seq_to_row,
  1088. ggml_backend_sched_t sched) {
  1089. if (dst == nullptr) {
  1090. return;
  1091. }
  1092. for (const auto & [seq_id, tensor] : tensor_map) {
  1093. auto it = seq_to_row.find(seq_id);
  1094. if (it == seq_to_row.end()) {
  1095. continue;
  1096. }
  1097. const uint32_t row = it->second;
  1098. GGML_ASSERT(row < counts.size());
  1099. GGML_ASSERT(ggml_is_contiguous(tensor) && "candidates tensor must be contiguous for async copy");
  1100. ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched, tensor);
  1101. llama_token * row_ptr = dst + (size_t) row * stride;
  1102. ggml_backend_tensor_get_async(backend, tensor, row_ptr, 0, ggml_nbytes(tensor));
  1103. // Update the actual number of candidates that were written.
  1104. counts[row] = ggml_nelements(tensor);
  1105. }
  1106. }
  1107. int llama_context::decode(const llama_batch & batch_inp) {
  1108. GGML_ASSERT((!batch_inp.token && batch_inp.embd) || (batch_inp.token && !batch_inp.embd)); // NOLINT
  1109. if (!memory) {
  1110. LLAMA_LOG_DEBUG("%s: cannot decode batches with this context (calling encode() instead)\n", __func__);
  1111. return encode(batch_inp);
  1112. }
  1113. if (batch_inp.n_tokens == 0) {
  1114. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  1115. return -1;
  1116. }
  1117. const auto & vocab = model.vocab;
  1118. const auto & hparams = model.hparams;
  1119. const int64_t n_vocab = vocab.n_tokens();
  1120. const int64_t n_embd = hparams.n_embd_inp();
  1121. // when computing embeddings, all tokens are output
  1122. const bool output_all = cparams.embeddings;
  1123. const bool has_samplers = !sampling.samplers.empty();
  1124. const uint32_t n_seq_max = cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max;
  1125. // TODO: avoid this workaround in the future
  1126. if (has_samplers && batch_inp.logits) {
  1127. std::vector<int32_t> seq_output_count(n_seq_max, 0);
  1128. for (int32_t i = 0; i < batch_inp.n_tokens; ++i) {
  1129. if (batch_inp.logits[i] == 0) {
  1130. continue;
  1131. }
  1132. const int ns = batch_inp.n_seq_id ? batch_inp.n_seq_id[i] : 1;
  1133. for (int32_t s = 0; s < ns; ++s) {
  1134. const llama_seq_id seq_id = batch_inp.seq_id ? batch_inp.seq_id[i][s] : 0;
  1135. seq_output_count[seq_id]++;
  1136. if (seq_output_count[seq_id] > 1) {
  1137. LLAMA_LOG_ERROR("%s: backend sampling requires at most one output token per sequence (seq_id %d had %d)\n",
  1138. __func__, seq_id, seq_output_count[seq_id]);
  1139. return -1;
  1140. }
  1141. }
  1142. }
  1143. }
  1144. if (!balloc->init(batch_inp, vocab, memory.get(), n_embd, n_seq_max, output_all)) {
  1145. LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
  1146. return -1;
  1147. }
  1148. const uint32_t n_tokens_all = balloc->get_n_tokens();
  1149. const uint32_t n_outputs_all = balloc->get_n_outputs();
  1150. if (output_all) {
  1151. // require that all tokens are output
  1152. if (n_outputs_all != n_tokens_all) {
  1153. LLAMA_LOG_ERROR("%s: pooled embedding requires that all tokens are output (n_outputs_all = %d, n_tokens_all = %d)\n",
  1154. __func__, n_outputs_all, n_tokens_all);
  1155. return -1;
  1156. }
  1157. }
  1158. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  1159. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  1160. if (t_compute_start_us == 0) {
  1161. t_compute_start_us = ggml_time_us();
  1162. }
  1163. n_queued_tokens += n_tokens_all;
  1164. // TODO: this clear of the buffer can easily be forgotten - need something better
  1165. embd_seq.clear();
  1166. output_swaps.clear();
  1167. bool did_optimize = false;
  1168. // handle any pending shifts/copies
  1169. memory_update(false);
  1170. llama_memory_context_ptr mctx;
  1171. while (true) {
  1172. mctx = memory->init_batch(*balloc, cparams.n_ubatch, output_all);
  1173. if (!mctx) {
  1174. return -2;
  1175. }
  1176. switch (mctx->get_status()) {
  1177. case LLAMA_MEMORY_STATUS_SUCCESS:
  1178. {
  1179. } break;
  1180. case LLAMA_MEMORY_STATUS_NO_UPDATE:
  1181. {
  1182. LLAMA_LOG_ERROR("%s: unexpected memory context status: %d\n", __func__, mctx->get_status());
  1183. return -2;
  1184. }
  1185. case LLAMA_MEMORY_STATUS_FAILED_PREPARE:
  1186. {
  1187. if (!did_optimize) {
  1188. did_optimize = true;
  1189. if (memory_update(true)) {
  1190. LLAMA_LOG_DEBUG("%s: retrying batch size %d after cache optimization\n", __func__, balloc->get_n_tokens());
  1191. continue;
  1192. }
  1193. }
  1194. LLAMA_LOG_WARN("%s: failed to find a memory slot for batch of size %d\n", __func__, balloc->get_n_tokens());
  1195. return 1;
  1196. }
  1197. case LLAMA_MEMORY_STATUS_FAILED_COMPUTE:
  1198. {
  1199. LLAMA_LOG_ERROR("%s: compute failed while preparing batch of size %d\n", __func__, balloc->get_n_tokens());
  1200. return -2;
  1201. }
  1202. }
  1203. break;
  1204. }
  1205. // reserve output buffer
  1206. if (output_reserve(n_outputs_all, balloc->get_batch()) < n_outputs_all) {
  1207. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all);
  1208. return -2;
  1209. };
  1210. int64_t n_outputs_prev = 0;
  1211. do {
  1212. const auto & ubatch = mctx->get_ubatch();
  1213. // count the outputs in this ubatch
  1214. {
  1215. int32_t n_outputs_new = 0;
  1216. if (n_outputs_all == n_tokens_all) {
  1217. n_outputs_new = ubatch.n_tokens;
  1218. } else {
  1219. for (uint32_t i = 0; i < ubatch.n_tokens; i++) {
  1220. n_outputs_new += (int32_t) (ubatch.output[i] != 0);
  1221. }
  1222. }
  1223. // needs to happen before the graph is built
  1224. n_outputs = n_outputs_new;
  1225. }
  1226. ggml_status status;
  1227. const auto * res = process_ubatch(ubatch, LLM_GRAPH_TYPE_DECODER, mctx.get(), status);
  1228. if (!res) {
  1229. // the last ubatch failed or was aborted -> remove all positions of that ubatch from the memory module
  1230. llama_pos pos_min[LLAMA_MAX_SEQ];
  1231. for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
  1232. pos_min[s] = std::numeric_limits<llama_pos>::max();
  1233. }
  1234. for (uint32_t i = 0; i < ubatch.n_tokens; ++i) {
  1235. const auto & seq_id = ubatch.seq_id[i][0];
  1236. pos_min[seq_id] = std::min(pos_min[seq_id], ubatch.pos[i]);
  1237. }
  1238. for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
  1239. if (pos_min[s] == std::numeric_limits<llama_pos>::max()) {
  1240. continue;
  1241. }
  1242. LLAMA_LOG_WARN("%s: removing memory module entries for seq_id = %d, pos = [%d, +inf)\n", __func__, s, pos_min[s]);
  1243. memory->seq_rm(s, pos_min[s], -1);
  1244. }
  1245. switch (status) {
  1246. case GGML_STATUS_ABORTED: return 2;
  1247. case GGML_STATUS_ALLOC_FAILED: return -2;
  1248. case GGML_STATUS_FAILED: return -3;
  1249. case GGML_STATUS_SUCCESS: GGML_ABORT("should not happen");
  1250. }
  1251. }
  1252. // plot the computation graph in dot format (for debugging purposes)
  1253. //if (n_past%100 == 0) {
  1254. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  1255. //}
  1256. auto * t_logits = res->get_logits();
  1257. auto * t_embd = cparams.embeddings ? res->get_embd() : nullptr;
  1258. if (t_embd && res->get_embd_pooled()) {
  1259. t_embd = res->get_embd_pooled();
  1260. }
  1261. // extract logits
  1262. // For multi-sequence batches that mix backend samplers and CPU sampler
  1263. // this is currently inefficient as we copy all logits even for the
  1264. // backend sampled tokens.
  1265. if (logits && t_logits && n_outputs > 0) {
  1266. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits);
  1267. GGML_ASSERT(backend_res != nullptr);
  1268. GGML_ASSERT(logits != nullptr);
  1269. float * logits_out = logits + n_outputs_prev*n_vocab;
  1270. if (n_outputs) {
  1271. GGML_ASSERT( n_outputs_prev + n_outputs <= n_outputs_all);
  1272. GGML_ASSERT((n_outputs_prev + n_outputs)*n_vocab <= (int64_t) logits_size);
  1273. ggml_backend_tensor_get_async(backend_res, t_logits, logits_out, 0, n_outputs*n_vocab*sizeof(float));
  1274. }
  1275. }
  1276. // extract embeddings
  1277. if (embd && t_embd && n_outputs > 0) {
  1278. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd);
  1279. GGML_ASSERT(backend_embd != nullptr);
  1280. switch (cparams.pooling_type) {
  1281. case LLAMA_POOLING_TYPE_NONE:
  1282. {
  1283. // extract token embeddings
  1284. GGML_ASSERT(embd != nullptr);
  1285. float * embd_out = embd + n_outputs_prev*n_embd;
  1286. if (n_outputs) {
  1287. GGML_ASSERT( n_outputs_prev + n_outputs <= n_outputs_all);
  1288. GGML_ASSERT((n_outputs_prev + n_outputs)*n_embd <= (int64_t) embd_size);
  1289. ggml_backend_tensor_get_async(backend_embd, t_embd, embd_out, 0, n_outputs*n_embd*sizeof(float));
  1290. }
  1291. } break;
  1292. case LLAMA_POOLING_TYPE_MEAN:
  1293. case LLAMA_POOLING_TYPE_CLS:
  1294. case LLAMA_POOLING_TYPE_LAST:
  1295. {
  1296. // extract sequence embeddings (cleared before processing each batch)
  1297. auto & embd_seq_out = embd_seq;
  1298. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  1299. const llama_seq_id seq_id = ubatch.seq_id_unq[s];
  1300. const int32_t seq_idx = ubatch.seq_idx[seq_id];
  1301. embd_seq_out[seq_id].resize(n_embd);
  1302. ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_embd*seq_idx)*sizeof(float), n_embd*sizeof(float));
  1303. }
  1304. } break;
  1305. case LLAMA_POOLING_TYPE_RANK:
  1306. {
  1307. // extract the rerank score - n_cls_out floats per sequence
  1308. auto & embd_seq_out = embd_seq;
  1309. const uint32_t n_cls_out = hparams.n_cls_out;
  1310. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  1311. const llama_seq_id seq_id = ubatch.seq_id_unq[s];
  1312. const int32_t seq_idx = ubatch.seq_idx[seq_id];
  1313. embd_seq_out[seq_id].resize(n_cls_out);
  1314. ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_cls_out*seq_idx)*sizeof(float), n_cls_out*sizeof(float));
  1315. }
  1316. } break;
  1317. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  1318. {
  1319. GGML_ABORT("unknown pooling type");
  1320. }
  1321. }
  1322. }
  1323. // This flag indicates whether a backend sampler has actually sampled a specific
  1324. // token, or if it has produced probabilites. If true, we can skip the normal copying of logits and embeddings.
  1325. const bool has_sampled = !res->t_sampled.empty() || !res->t_sampled_probs.empty() || !res->t_sampled_logits.empty();
  1326. if (has_samplers && has_sampled) {
  1327. const auto seq_to_output_row = build_seq_to_output_row(ubatch, n_outputs_prev);
  1328. const auto stride = n_vocab;
  1329. // async copy the sampling data from the backend to the host
  1330. copy_tensor_async_ints(res->t_sampled, sampling.sampled, sampling.sampled_size, seq_to_output_row, sched.get());
  1331. copy_tensor_async_floats (res->t_sampled_logits, sampling.logits, stride, sampling.logits_count, seq_to_output_row, sched.get());
  1332. copy_tensor_async_floats (res->t_sampled_probs, sampling.probs, stride, sampling.probs_count, seq_to_output_row, sched.get());
  1333. copy_tensor_async_candidates(res->t_candidates, sampling.candidates, stride, sampling.candidates_count, seq_to_output_row, sched.get());
  1334. }
  1335. n_outputs_prev += n_outputs;
  1336. } while (mctx->next());
  1337. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  1338. n_outputs = n_outputs_all;
  1339. // set output mappings
  1340. if (n_outputs > 0) {
  1341. bool sorted_output = true;
  1342. auto & out_ids = balloc->get_out_ids();
  1343. GGML_ASSERT(out_ids.size() == (size_t) n_outputs);
  1344. for (int64_t i = 0; i < n_outputs; ++i) {
  1345. int64_t out_id = out_ids[i];
  1346. output_ids[out_id] = i;
  1347. if (out_id != i) {
  1348. sorted_output = false;
  1349. }
  1350. }
  1351. // make the outputs have the same order they had in the user-provided batch
  1352. // note: this is mostly relevant for recurrent models atm
  1353. if (!sorted_output && n_outputs > 1) {
  1354. GGML_ASSERT((size_t) n_outputs == out_ids.size());
  1355. // TODO: is there something more efficient which also minimizes swaps?
  1356. // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
  1357. for (uint32_t i = 0; i < n_outputs - 1; ++i) {
  1358. uint32_t j_min = i;
  1359. for (uint32_t j = i + 1; j < n_outputs; ++j) {
  1360. if (out_ids[j] < out_ids[j_min]) {
  1361. j_min = j;
  1362. }
  1363. }
  1364. if (j_min == i) {
  1365. continue;
  1366. }
  1367. std::swap(out_ids[i], out_ids[j_min]);
  1368. // remember the swaps and apply them lazily upon logits/embeddings access
  1369. output_swaps.push_back({ i, j_min });
  1370. }
  1371. std::fill(output_ids.begin(), output_ids.end(), -1);
  1372. for (uint32_t i = 0; i < n_outputs; ++i) {
  1373. output_ids[out_ids[i]] = i;
  1374. }
  1375. }
  1376. }
  1377. // wait for the computation to finish (automatically done when obtaining the model output)
  1378. //synchronize();
  1379. return 0;
  1380. }
  1381. //
  1382. // output
  1383. //
  1384. uint32_t llama_context::output_reserve(int32_t n_outputs, const llama_batch & batch) {
  1385. const auto & hparams = model.hparams;
  1386. const auto & vocab = model.vocab;
  1387. const int64_t n_outputs_max = std::max<int64_t>(n_outputs, n_seq_max());
  1388. const auto n_batch = cparams.n_batch;
  1389. const auto n_vocab = vocab.n_tokens();
  1390. const auto n_embd = hparams.n_embd;
  1391. bool has_logits = true;
  1392. bool has_embd = cparams.embeddings;
  1393. // TODO: hacky enc-dec support
  1394. if (model.arch == LLM_ARCH_T5) {
  1395. has_logits = true;
  1396. has_embd = true;
  1397. }
  1398. // Check which sampling modes are needed for the current batch.
  1399. // TODO: avoid this branching by working with the worst-case
  1400. bool has_sampling = false;
  1401. bool cpu_logits = false;
  1402. if (batch.logits) {
  1403. for (int32_t i = 0; i < batch.n_tokens; i++) {
  1404. if (!batch.logits[i]) {
  1405. continue;
  1406. }
  1407. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1408. llama_seq_id seq_id = batch.seq_id[i][j];
  1409. if (sampling.samplers.find(seq_id) != sampling.samplers.end()) {
  1410. has_sampling = true;
  1411. } else {
  1412. cpu_logits = true;
  1413. }
  1414. }
  1415. }
  1416. } else {
  1417. // When batch.logits is nullptr (when loading state with a dummy batch),
  1418. // allocate CPU logits.
  1419. cpu_logits = true;
  1420. }
  1421. size_t backend_float_count = 0;
  1422. size_t backend_token_count = 0;
  1423. // Allocate CPU logits buffer only if needed by sequences in this batch
  1424. logits_size = (has_logits && cpu_logits) ? n_vocab*n_outputs_max : 0;
  1425. embd_size = has_embd ? n_embd*n_outputs_max : 0;
  1426. // TODO: avoid this branching by working with the worst-case
  1427. if (!has_sampling) {
  1428. sampling.logits_size = 0;
  1429. sampling.probs_size = 0;
  1430. sampling.sampled_size = 0;
  1431. sampling.candidates_size = 0;
  1432. } else {
  1433. sampling.logits_size = n_vocab*n_outputs_max;
  1434. sampling.probs_size = n_vocab*n_outputs_max;
  1435. sampling.sampled_size = n_outputs_max;
  1436. sampling.candidates_size = n_vocab*n_outputs_max;
  1437. backend_float_count = sampling.logits_size + sampling.probs_size;
  1438. backend_token_count = sampling.sampled_size + sampling.candidates_size;
  1439. }
  1440. if (output_ids.empty()) {
  1441. // init, never resized afterwards
  1442. output_ids.resize(n_batch);
  1443. }
  1444. const size_t prev_size = buf_output ? ggml_backend_buffer_get_size(buf_output.get()) : 0;
  1445. const size_t new_size =
  1446. (logits_size + embd_size + backend_float_count) * sizeof(float) +
  1447. ( backend_token_count) * sizeof(llama_token);
  1448. // alloc only when more than the current capacity is required
  1449. // TODO: also consider shrinking the buffer
  1450. if (!buf_output || prev_size < new_size) {
  1451. if (buf_output) {
  1452. #ifndef NDEBUG
  1453. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  1454. LLAMA_LOG_DEBUG("%s: reallocating output buffer from size %.02f MiB to %.02f MiB\n", __func__, prev_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
  1455. #endif
  1456. synchronize();
  1457. // TODO: not needed?
  1458. buf_output = nullptr;
  1459. logits = nullptr;
  1460. embd = nullptr;
  1461. }
  1462. auto * buft = ggml_backend_cpu_buffer_type();
  1463. // try to use the host buffer of the device where the output tensor is allocated for faster transfer to system memory
  1464. auto * output_dev = model.dev_output();
  1465. auto * output_dev_host_buft = output_dev ? ggml_backend_dev_host_buffer_type(output_dev) : nullptr;
  1466. if (output_dev_host_buft) {
  1467. buft = output_dev_host_buft;
  1468. }
  1469. buf_output.reset(ggml_backend_buft_alloc_buffer(buft, new_size));
  1470. if (buf_output == nullptr) {
  1471. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  1472. return 0;
  1473. }
  1474. }
  1475. float * output_base = (float *) ggml_backend_buffer_get_base(buf_output.get());
  1476. logits = nullptr;
  1477. embd = nullptr;
  1478. size_t offset = 0;
  1479. uint8_t * base = (uint8_t *) output_base;
  1480. logits = (has_logits && cpu_logits) ? output_base : nullptr;
  1481. offset += logits_size * sizeof(float);
  1482. embd = has_embd ? (float *) (base + offset) : nullptr;
  1483. offset += embd_size * sizeof(float);
  1484. sampling.logits = nullptr;
  1485. sampling.probs = nullptr;
  1486. sampling.sampled = nullptr;
  1487. sampling.candidates = nullptr;
  1488. if (has_sampling) {
  1489. sampling.logits = (float *) (base + offset);
  1490. offset += sampling.logits_size * sizeof(float);
  1491. sampling.probs = (float *) (base + offset);
  1492. offset += sampling.probs_size * sizeof(float);
  1493. sampling.sampled = (llama_token *) (base + offset);
  1494. offset += sampling.sampled_size * sizeof(llama_token);
  1495. sampling.candidates = (llama_token *) (base + offset);
  1496. offset += sampling.candidates_size * sizeof(llama_token);
  1497. // The count vectors keep track of the actual number of logits/probs/candidates
  1498. // copied from the backend for each output row.
  1499. sampling.logits_count.resize(n_outputs_max);
  1500. sampling.probs_count.resize(n_outputs_max);
  1501. sampling.candidates_count.resize(n_outputs_max);
  1502. std::fill(sampling.logits_count.begin(), sampling.logits_count.end(), 0);
  1503. std::fill(sampling.probs_count.begin(), sampling.probs_count.end(), 0);
  1504. std::fill(sampling.candidates_count.begin(), sampling.candidates_count.end(), 0);
  1505. std::fill_n(sampling.sampled, sampling.sampled_size, LLAMA_TOKEN_NULL);
  1506. }
  1507. // set all ids as invalid (negative)
  1508. std::fill(output_ids.begin(), output_ids.end(), -1);
  1509. this->n_outputs = 0;
  1510. return n_outputs_max;
  1511. }
  1512. void llama_context::output_reorder() {
  1513. const uint64_t n_vocab = model.vocab.n_tokens();
  1514. const uint64_t n_embd = model.hparams.n_embd;
  1515. for (size_t s = 0; s < output_swaps.size(); ++s) {
  1516. const uint64_t i0 = output_swaps[s].i0;
  1517. const uint64_t i1 = output_swaps[s].i1;
  1518. if (logits_size > 0) {
  1519. for (uint64_t k = 0; k < n_vocab; k++) {
  1520. std::swap(logits[i0*n_vocab + k], logits[i1*n_vocab + k]);
  1521. }
  1522. }
  1523. if (embd_size > 0) {
  1524. for (uint64_t k = 0; k < n_embd; k++) {
  1525. std::swap(embd[i0*n_embd + k], embd[i1*n_embd + k]);
  1526. }
  1527. }
  1528. if (sampling.logits && sampling.logits_size > 0) {
  1529. for (uint64_t k = 0; k < n_vocab; ++k) {
  1530. std::swap(sampling.logits[i0*n_vocab + k], sampling.logits[i1*n_vocab + k]);
  1531. }
  1532. }
  1533. if (sampling.probs && sampling.probs_size > 0) {
  1534. for (uint64_t k = 0; k < n_vocab; ++k) {
  1535. std::swap(sampling.probs[i0*n_vocab + k], sampling.probs[i1*n_vocab + k]);
  1536. }
  1537. }
  1538. if (sampling.candidates && sampling.candidates_size > 0) {
  1539. for (uint64_t k = 0; k < n_vocab; ++k) {
  1540. std::swap(sampling.candidates[i0*n_vocab + k], sampling.candidates[i1*n_vocab + k]);
  1541. }
  1542. }
  1543. if (sampling.sampled && sampling.sampled_size > 0) {
  1544. std::swap(sampling.sampled[i0], sampling.sampled[i1]);
  1545. }
  1546. if (!sampling.logits_count.empty()) {
  1547. std::swap(sampling.logits_count[i0], sampling.logits_count[i1]);
  1548. }
  1549. if (!sampling.probs_count.empty()) {
  1550. std::swap(sampling.probs_count[i0], sampling.probs_count[i1]);
  1551. }
  1552. if (!sampling.candidates_count.empty()) {
  1553. std::swap(sampling.candidates_count[i0], sampling.candidates_count[i1]);
  1554. }
  1555. }
  1556. output_swaps.clear();
  1557. }
  1558. //
  1559. // graph
  1560. //
  1561. uint32_t llama_context::graph_max_nodes(uint32_t n_tokens) const {
  1562. if (model.arch == LLM_ARCH_QWEN3NEXT) {
  1563. return std::max<uint32_t>(n_tokens * 40, 32u * model.n_tensors());
  1564. }
  1565. uint32_t res = std::max<uint32_t>(1024u, 8u*model.n_tensors());
  1566. res += model.n_lora_nodes;
  1567. return res;
  1568. }
  1569. llm_graph_result * llama_context::get_gf_res_reserve() const {
  1570. return static_cast<llm_graph_result *>(gf_res_reserve.get());
  1571. }
  1572. ggml_cgraph * llama_context::graph_reserve(
  1573. uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx, bool split_only, size_t * sizes) {
  1574. LLAMA_LOG_DEBUG("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n", __func__, n_tokens, n_seqs, n_outputs);
  1575. GGML_ASSERT(n_outputs >= 1);
  1576. if (n_tokens % n_seqs != 0) {
  1577. n_tokens = ((n_tokens + (n_seqs - 1)) / n_seqs) * n_seqs; // round to next multiple of n_seqs
  1578. n_outputs = std::max(n_outputs, n_tokens);
  1579. LLAMA_LOG_DEBUG("%s: making n_tokens a multiple of n_seqs - n_tokens = %u, n_seqs = %u, n_outputs = %u\n", __func__, n_tokens, n_seqs, n_outputs);
  1580. }
  1581. ggml_backend_sched_reset(sched.get());
  1582. // when the scheduler is reset, we cannnot reuse the old graph, so we reset the previous graph result to prevent that
  1583. gf_res_prev->reset();
  1584. // store the n_outputs as it is, and restore it afterwards
  1585. // TODO: not sure if needed, might simplify in the future by removing this
  1586. const auto save_n_outputs = this->n_outputs;
  1587. this->n_outputs = n_outputs;
  1588. llama_batch_allocr balloc(model.hparams.n_pos_per_embd());
  1589. llama_ubatch ubatch = balloc.ubatch_reserve(n_tokens/n_seqs, n_seqs);
  1590. // set one output token per sequence in order to activate all backend samplers
  1591. std::vector<llama_seq_id> seq_ids(n_seqs);
  1592. for (uint32_t i = 0; i < n_seqs; ++i) {
  1593. seq_ids[i] = i;
  1594. ubatch.n_seq_id[i] = 1;
  1595. ubatch.seq_id[i] = &seq_ids[i];
  1596. ubatch.output[i] = true;
  1597. }
  1598. auto * res = gf_res_reserve.get();
  1599. const auto gparams = graph_params(res, ubatch, mctx, LLM_GRAPH_TYPE_DEFAULT);
  1600. res->reset();
  1601. auto * gf = model.build_graph(gparams);
  1602. this->n_outputs = save_n_outputs;
  1603. // initialize scheduler with the specified graph
  1604. if (split_only) {
  1605. if (sizes) {
  1606. ggml_backend_sched_reserve_size(sched.get(), gf, sizes);
  1607. } else {
  1608. ggml_backend_sched_split_graph(sched.get(), gf);
  1609. }
  1610. } else if (!ggml_backend_sched_reserve(sched.get(), gf)) {
  1611. GGML_ASSERT(!sizes);
  1612. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  1613. return nullptr;
  1614. }
  1615. return gf;
  1616. }
  1617. llm_graph_params llama_context::graph_params(
  1618. llm_graph_result * res,
  1619. const llama_ubatch & ubatch,
  1620. const llama_memory_context_i * mctx,
  1621. llm_graph_type gtype) const {
  1622. return {
  1623. /*.arch =*/ model.arch,
  1624. /*.hparams =*/ model.hparams,
  1625. /*.cparams =*/ cparams,
  1626. /*.ubatch =*/ ubatch,
  1627. /*.gtype =*/ gtype,
  1628. /*.sched =*/ sched.get(),
  1629. /*.backend_cpu =*/ backend_cpu,
  1630. /*.cvec =*/ &cvec,
  1631. /*.loras =*/ &loras,
  1632. /*.mctx =*/ mctx,
  1633. /*.cross =*/ &cross,
  1634. /*.samplers =*/ sampling.samplers,
  1635. /*.n_outputs =*/ n_outputs,
  1636. /*.cb =*/ graph_get_cb(),
  1637. /*.res =*/ res,
  1638. };
  1639. }
  1640. ggml_status llama_context::graph_compute(
  1641. ggml_cgraph * gf,
  1642. bool batched) {
  1643. int n_threads = batched ? cparams.n_threads_batch : cparams.n_threads;
  1644. ggml_threadpool_t tp = batched ? threadpool_batch : threadpool;
  1645. if (backend_cpu != nullptr) {
  1646. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend_cpu));
  1647. auto * set_threadpool_fn = (decltype(ggml_backend_cpu_set_threadpool) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_set_threadpool");
  1648. if (set_threadpool_fn) {
  1649. set_threadpool_fn(backend_cpu, tp);
  1650. }
  1651. }
  1652. // set the number of threads for all the backends
  1653. for (const auto & set_n_threads_fn : set_n_threads_fns) {
  1654. set_n_threads_fn.second(set_n_threads_fn.first, n_threads);
  1655. }
  1656. auto status = ggml_backend_sched_graph_compute_async(sched.get(), gf);
  1657. if (status != GGML_STATUS_SUCCESS) {
  1658. LLAMA_LOG_ERROR("%s: ggml_backend_sched_graph_compute_async failed with error %d\n", __func__, status);
  1659. }
  1660. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(sched));
  1661. return status;
  1662. }
  1663. llm_graph_cb llama_context::graph_get_cb() const {
  1664. return [&](const llama_ubatch & ubatch, ggml_tensor * cur, const char * name, int il) {
  1665. if (il >= 0) {
  1666. ggml_format_name(cur, "%s-%d", name, il);
  1667. } else {
  1668. ggml_set_name(cur, name);
  1669. }
  1670. if (!cparams.offload_kqv) {
  1671. if (strcmp(name, "kqv_merged_cont") == 0) {
  1672. // all nodes between the KV store and the attention output are run on the CPU
  1673. ggml_backend_sched_set_tensor_backend(sched.get(), cur, backend_cpu);
  1674. }
  1675. }
  1676. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  1677. // FIXME: fix in ggml_backend_sched
  1678. const bool full_offload = model.n_gpu_layers() > model.hparams.n_layer;
  1679. if (ubatch.n_tokens < 32 || full_offload) {
  1680. if (il != -1 && strcmp(name, "norm") == 0) {
  1681. const auto & dev_layer = model.dev_layer(il);
  1682. for (const auto & backend : backends) {
  1683. if (ggml_backend_get_device(backend.get()) == dev_layer) {
  1684. if (ggml_backend_supports_op(backend.get(), cur)) {
  1685. ggml_backend_sched_set_tensor_backend(sched.get(), cur, backend.get());
  1686. }
  1687. }
  1688. }
  1689. }
  1690. }
  1691. };
  1692. }
  1693. //
  1694. // state save/load
  1695. //
  1696. class llama_io_write_dummy : public llama_io_write_i {
  1697. public:
  1698. llama_io_write_dummy() = default;
  1699. void write(const void * /* src */, size_t size) override {
  1700. size_written += size;
  1701. }
  1702. void write_tensor(const ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
  1703. size_written += size;
  1704. }
  1705. size_t n_bytes() override {
  1706. return size_written;
  1707. }
  1708. private:
  1709. size_t size_written = 0;
  1710. };
  1711. class llama_io_write_buffer : public llama_io_write_i {
  1712. public:
  1713. llama_io_write_buffer(
  1714. uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  1715. void write(const void * src, size_t size) override {
  1716. if (size > buf_size) {
  1717. throw std::runtime_error("unexpectedly reached end of buffer");
  1718. }
  1719. memcpy(ptr, src, size);
  1720. ptr += size;
  1721. size_written += size;
  1722. buf_size -= size;
  1723. }
  1724. void write_tensor(const ggml_tensor * tensor, size_t offset, size_t size) override {
  1725. if (size > buf_size) {
  1726. throw std::runtime_error("unexpectedly reached end of buffer");
  1727. }
  1728. ggml_backend_tensor_get(tensor, ptr, offset, size);
  1729. ptr += size;
  1730. size_written += size;
  1731. buf_size -= size;
  1732. }
  1733. size_t n_bytes() override {
  1734. return size_written;
  1735. }
  1736. private:
  1737. uint8_t * ptr;
  1738. size_t buf_size = 0;
  1739. size_t size_written = 0;
  1740. };
  1741. class llama_io_read_buffer : public llama_io_read_i {
  1742. public:
  1743. llama_io_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  1744. const uint8_t * read(size_t size) override {
  1745. const uint8_t * base_ptr = ptr;
  1746. if (size > buf_size) {
  1747. throw std::runtime_error("unexpectedly reached end of buffer");
  1748. }
  1749. ptr += size;
  1750. size_read += size;
  1751. buf_size -= size;
  1752. return base_ptr;
  1753. }
  1754. void read_to(void * dst, size_t size) override {
  1755. memcpy(dst, read(size), size);
  1756. }
  1757. size_t n_bytes() override {
  1758. return size_read;
  1759. }
  1760. private:
  1761. const uint8_t * ptr;
  1762. size_t buf_size = 0;
  1763. size_t size_read = 0;
  1764. };
  1765. class llama_io_write_file : public llama_io_write_i {
  1766. public:
  1767. llama_io_write_file(llama_file * f) : file(f) {}
  1768. void write(const void * src, size_t size) override {
  1769. file->write_raw(src, size);
  1770. size_written += size;
  1771. }
  1772. void write_tensor(const ggml_tensor * tensor, size_t offset, size_t size) override {
  1773. temp_buffer.resize(size);
  1774. ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
  1775. write(temp_buffer.data(), temp_buffer.size());
  1776. }
  1777. size_t n_bytes() override {
  1778. return size_written;
  1779. }
  1780. private:
  1781. llama_file * file;
  1782. size_t size_written = 0;
  1783. std::vector<uint8_t> temp_buffer;
  1784. };
  1785. class llama_io_read_file : public llama_io_read_i {
  1786. public:
  1787. llama_io_read_file(llama_file * f) : file(f) {}
  1788. void read_to(void * dst, size_t size) override {
  1789. file->read_raw(dst, size);
  1790. size_read += size;
  1791. }
  1792. const uint8_t * read(size_t size) override {
  1793. temp_buffer.resize(size);
  1794. read_to(temp_buffer.data(), size);
  1795. return temp_buffer.data();
  1796. }
  1797. size_t n_bytes() override {
  1798. return size_read;
  1799. }
  1800. private:
  1801. llama_file * file;
  1802. size_t size_read = 0;
  1803. std::vector<uint8_t> temp_buffer;
  1804. };
  1805. size_t llama_context::state_get_size() {
  1806. llama_io_write_dummy io;
  1807. try {
  1808. return state_write_data(io);
  1809. } catch (const std::exception & err) {
  1810. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  1811. return 0;
  1812. }
  1813. }
  1814. size_t llama_context::state_get_data(uint8_t * dst, size_t size) {
  1815. llama_io_write_buffer io(dst, size);
  1816. try {
  1817. return state_write_data(io);
  1818. } catch (const std::exception & err) {
  1819. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  1820. return 0;
  1821. }
  1822. }
  1823. size_t llama_context::state_set_data(const uint8_t * src, size_t size) {
  1824. llama_io_read_buffer io(src, size);
  1825. try {
  1826. return state_read_data(io);
  1827. } catch (const std::exception & err) {
  1828. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  1829. return 0;
  1830. }
  1831. }
  1832. size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_flags flags) {
  1833. llama_io_write_dummy io;
  1834. try {
  1835. return state_seq_write_data(io, seq_id, flags);
  1836. } catch (const std::exception & err) {
  1837. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  1838. return 0;
  1839. }
  1840. }
  1841. size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, size_t size, llama_state_seq_flags flags) {
  1842. llama_io_write_buffer io(dst, size);
  1843. try {
  1844. return state_seq_write_data(io, seq_id, flags);
  1845. } catch (const std::exception & err) {
  1846. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  1847. return 0;
  1848. }
  1849. }
  1850. size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * src, size_t size, llama_state_seq_flags flags) {
  1851. llama_io_read_buffer io(src, size);
  1852. try {
  1853. return state_seq_read_data(io, seq_id, flags);
  1854. } catch (const std::exception & err) {
  1855. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  1856. return 0;
  1857. }
  1858. }
  1859. bool llama_context::state_load_file(const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  1860. llama_file file(filepath, "rb");
  1861. // sanity checks
  1862. {
  1863. const uint32_t magic = file.read_u32();
  1864. const uint32_t version = file.read_u32();
  1865. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  1866. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  1867. return false;
  1868. }
  1869. }
  1870. // load the prompt
  1871. {
  1872. const uint32_t n_token_count = file.read_u32();
  1873. if (n_token_count > n_token_capacity) {
  1874. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  1875. return false;
  1876. }
  1877. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  1878. *n_token_count_out = n_token_count;
  1879. }
  1880. // restore the context state
  1881. {
  1882. const size_t n_state_size_cur = file.size() - file.tell();
  1883. llama_io_read_file io( &file);
  1884. const size_t n_read = state_read_data(io);
  1885. if (n_read != n_state_size_cur) {
  1886. LLAMA_LOG_ERROR("%s: did not read all of the session file data! size %zu, got %zu\n", __func__, n_state_size_cur, n_read);
  1887. return false;
  1888. }
  1889. }
  1890. return true;
  1891. }
  1892. bool llama_context::state_save_file(const char * filepath, const llama_token * tokens, size_t n_token_count) {
  1893. llama_file file(filepath, "wb");
  1894. file.write_u32(LLAMA_SESSION_MAGIC);
  1895. file.write_u32(LLAMA_SESSION_VERSION);
  1896. // save the prompt
  1897. file.write_u32((uint32_t) n_token_count);
  1898. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  1899. // save the context state using stream saving
  1900. llama_io_write_file io(&file);
  1901. state_write_data(io);
  1902. return true;
  1903. }
  1904. size_t llama_context::state_seq_load_file(llama_seq_id seq_id, const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  1905. llama_file file(filepath, "rb");
  1906. // version checks
  1907. {
  1908. const uint32_t magic = file.read_u32();
  1909. const uint32_t version = file.read_u32();
  1910. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  1911. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  1912. return 0;
  1913. }
  1914. }
  1915. // load the prompt
  1916. {
  1917. const uint32_t n_token_count = file.read_u32();
  1918. if (n_token_count > n_token_capacity) {
  1919. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  1920. return 0;
  1921. }
  1922. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  1923. *n_token_count_out = n_token_count;
  1924. }
  1925. // restore the context state
  1926. {
  1927. const size_t state_size = file.size() - file.tell();
  1928. llama_io_read_file io(&file);
  1929. const size_t nread = state_seq_read_data(io, seq_id, 0);
  1930. if (!nread) {
  1931. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  1932. return 0;
  1933. }
  1934. GGML_ASSERT(nread <= state_size);
  1935. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  1936. }
  1937. return file.tell();
  1938. }
  1939. size_t llama_context::state_seq_save_file(llama_seq_id seq_id, const char * filepath, const llama_token * tokens, size_t n_token_count) {
  1940. llama_file file(filepath, "wb");
  1941. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  1942. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  1943. // save the prompt
  1944. file.write_u32((uint32_t) n_token_count);
  1945. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  1946. // save the context state using stream saving
  1947. llama_io_write_file io(&file);
  1948. state_seq_write_data(io, seq_id, 0);
  1949. const size_t res = file.tell();
  1950. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + io.n_bytes());
  1951. return res;
  1952. }
  1953. size_t llama_context::state_write_data(llama_io_write_i & io) {
  1954. LLAMA_LOG_DEBUG("%s: writing state\n", __func__);
  1955. // write model info
  1956. {
  1957. LLAMA_LOG_DEBUG("%s: - writing model info\n", __func__);
  1958. const std::string arch_str = llm_arch_name(model.arch);
  1959. io.write_string(arch_str);
  1960. // TODO: add more model-specific info which should prevent loading the session file if not identical
  1961. }
  1962. // write output ids
  1963. {
  1964. LLAMA_LOG_DEBUG("%s: - writing output ids\n", __func__);
  1965. const auto n_outputs = this->n_outputs;
  1966. const auto & output_ids = this->output_ids;
  1967. std::vector<int32_t> w_output_pos;
  1968. w_output_pos.resize(n_outputs);
  1969. // build a more compact representation of the output ids
  1970. for (size_t i = 0; i < n_batch(); ++i) {
  1971. // map an output id to a position in the batch
  1972. int64_t pos = output_ids[i];
  1973. if (pos >= 0) {
  1974. GGML_ASSERT(pos < n_outputs);
  1975. w_output_pos[pos] = i;
  1976. }
  1977. }
  1978. io.write(&n_outputs, sizeof(n_outputs));
  1979. if (n_outputs) {
  1980. io.write(w_output_pos.data(), n_outputs * sizeof(int32_t));
  1981. }
  1982. }
  1983. // write logits
  1984. {
  1985. LLAMA_LOG_DEBUG("%s: - writing logits\n", __func__);
  1986. const uint64_t logits_size = std::min((uint64_t) this->logits_size, (uint64_t) n_outputs * model.vocab.n_tokens());
  1987. io.write(&logits_size, sizeof(logits_size));
  1988. if (logits_size) {
  1989. io.write(logits, logits_size * sizeof(float));
  1990. }
  1991. }
  1992. // write embeddings
  1993. {
  1994. LLAMA_LOG_DEBUG("%s: - writing embeddings\n", __func__);
  1995. const uint64_t embd_size = std::min((uint64_t) this->embd_size, (uint64_t) n_outputs * model.hparams.n_embd);
  1996. io.write(&embd_size, sizeof(embd_size));
  1997. if (embd_size) {
  1998. io.write(embd, embd_size * sizeof(float));
  1999. }
  2000. }
  2001. // TODO: handle sampling buffers and samplers state ?
  2002. // https://github.com/ggml-org/llama.cpp/pull/17004
  2003. if (memory != nullptr) {
  2004. LLAMA_LOG_DEBUG("%s: - writing memory module\n", __func__);
  2005. memory->state_write(io);
  2006. }
  2007. return io.n_bytes();
  2008. }
  2009. size_t llama_context::state_read_data(llama_io_read_i & io) {
  2010. LLAMA_LOG_DEBUG("%s: reading state\n", __func__);
  2011. // read model info
  2012. {
  2013. LLAMA_LOG_DEBUG("%s: - reading model info\n", __func__);
  2014. const std::string cur_arch_str = llm_arch_name(model.arch);
  2015. std::string arch_str;
  2016. io.read_string(arch_str);
  2017. if (cur_arch_str != arch_str) {
  2018. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  2019. }
  2020. // TODO: add more info which needs to be identical but which is not verified otherwise
  2021. }
  2022. // read output ids
  2023. {
  2024. LLAMA_LOG_DEBUG("%s: - reading output ids\n", __func__);
  2025. auto n_outputs = this->n_outputs;
  2026. io.read_to(&n_outputs, sizeof(n_outputs));
  2027. // Create a dummy batch for state loading.
  2028. llama_batch dummy_batch = {};
  2029. dummy_batch.n_tokens = 0;
  2030. if (n_outputs > output_reserve(n_outputs, dummy_batch)) {
  2031. throw std::runtime_error("could not reserve outputs");
  2032. }
  2033. std::vector<int32_t> output_pos;
  2034. if (n_outputs) {
  2035. output_pos.resize(n_outputs);
  2036. io.read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  2037. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  2038. int32_t id = output_pos[i];
  2039. if ((uint32_t) id >= n_batch()) {
  2040. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, n_batch()));
  2041. }
  2042. this->output_ids[id] = i;
  2043. }
  2044. this->n_outputs = n_outputs;
  2045. }
  2046. }
  2047. // read logits
  2048. {
  2049. LLAMA_LOG_DEBUG("%s: - reading logits\n", __func__);
  2050. uint64_t logits_size;
  2051. io.read_to(&logits_size, sizeof(logits_size));
  2052. if (this->logits_size < logits_size) {
  2053. throw std::runtime_error("logits buffer too small");
  2054. }
  2055. if (logits_size) {
  2056. io.read_to(this->logits, logits_size * sizeof(float));
  2057. }
  2058. }
  2059. // read embeddings
  2060. {
  2061. LLAMA_LOG_DEBUG("%s: - reading embeddings\n", __func__);
  2062. uint64_t embd_size;
  2063. io.read_to(&embd_size, sizeof(embd_size));
  2064. if (this->embd_size < embd_size) {
  2065. throw std::runtime_error("embeddings buffer too small");
  2066. }
  2067. if (embd_size) {
  2068. io.read_to(this->embd, embd_size * sizeof(float));
  2069. }
  2070. }
  2071. // TODO: handle sampling buffers and samplers state ?
  2072. // https://github.com/ggml-org/llama.cpp/pull/17004
  2073. if (memory) {
  2074. LLAMA_LOG_DEBUG("%s: - reading memory module\n", __func__);
  2075. memory->state_read(io);
  2076. }
  2077. return io.n_bytes();
  2078. }
  2079. size_t llama_context::state_seq_write_data(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
  2080. GGML_UNUSED(seq_id);
  2081. if (memory) {
  2082. memory->state_write(io, seq_id, flags);
  2083. }
  2084. return io.n_bytes();
  2085. }
  2086. size_t llama_context::state_seq_read_data(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
  2087. GGML_UNUSED(seq_id);
  2088. if (memory) {
  2089. memory->state_read(io, seq_id, flags);
  2090. }
  2091. return io.n_bytes();
  2092. }
  2093. //
  2094. // perf
  2095. //
  2096. llama_perf_context_data llama_context::perf_get_data() const {
  2097. llama_perf_context_data data = {};
  2098. data.t_start_ms = 1e-3 * t_start_us;
  2099. data.t_load_ms = 1e-3 * t_load_us;
  2100. data.t_p_eval_ms = 1e-3 * t_p_eval_us;
  2101. data.t_eval_ms = 1e-3 * t_eval_us;
  2102. data.n_p_eval = std::max(1, n_p_eval);
  2103. data.n_eval = std::max(1, n_eval);
  2104. data.n_reused = std::max(0, n_reused);
  2105. return data;
  2106. }
  2107. void llama_context::perf_reset() {
  2108. t_start_us = ggml_time_us();
  2109. t_eval_us = n_eval = 0;
  2110. t_p_eval_us = n_p_eval = 0;
  2111. n_reused = 0;
  2112. }
  2113. std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> llama_context::memory_breakdown() const {
  2114. std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> ret;
  2115. for (const auto & [buft, size] : model.memory_breakdown()) {
  2116. ret[buft].model += size;
  2117. }
  2118. if (memory) {
  2119. for (const auto & [buft, size] : memory->memory_breakdown()) {
  2120. ret[buft].context += size;
  2121. }
  2122. }
  2123. if (model.hparams.no_alloc) {
  2124. for (size_t i = 0; i < backends.size(); ++i) {
  2125. ggml_backend_t backend = backends[i].get();
  2126. ggml_backend_buffer_type_t buft = ggml_backend_sched_get_buffer_type(sched.get(), backend);
  2127. ret[buft].compute += backend_buf_exp_size[i];
  2128. }
  2129. } else {
  2130. for (const auto & backend_ptr : backends) {
  2131. ggml_backend_t backend = backend_ptr.get();
  2132. ggml_backend_buffer_type_t buft = ggml_backend_sched_get_buffer_type(sched.get(), backend);
  2133. ret[buft].compute += ggml_backend_sched_get_buffer_size(sched.get(), backend);
  2134. }
  2135. }
  2136. return ret;
  2137. }
  2138. //
  2139. // training
  2140. //
  2141. static void llama_set_param(struct ggml_tensor * tensor, llama_opt_param_filter param_filter, void * userdata) {
  2142. if (!tensor || tensor->type != GGML_TYPE_F32) {
  2143. return;
  2144. }
  2145. if (!param_filter(tensor, userdata)) {
  2146. return;
  2147. }
  2148. if (strcmp(tensor->name, "token_embd.weight") == 0) {
  2149. return; // FIXME
  2150. }
  2151. if (strcmp(tensor->name, "rope_freqs.weight") == 0) {
  2152. return; // FIXME
  2153. }
  2154. ggml_set_param(tensor);
  2155. }
  2156. void llama_context::opt_init(struct llama_model * model, struct llama_opt_params lopt_params) {
  2157. GGML_ASSERT(!opt_ctx);
  2158. model->hparams.n_ctx_train = lopt_params.n_ctx_train > 0 ? lopt_params.n_ctx_train : n_ctx();
  2159. const uint32_t n_batch = std::min(this->n_batch(), model->hparams.n_ctx_train);
  2160. const uint32_t n_ubatch = std::min(this->n_ubatch(), n_batch);
  2161. GGML_ASSERT(model->hparams.n_ctx_train % n_batch == 0);
  2162. GGML_ASSERT(n_batch % n_ubatch == 0);
  2163. ggml_opt_params opt_params = ggml_opt_default_params(sched.get(), GGML_OPT_LOSS_TYPE_CROSS_ENTROPY);
  2164. opt_params.opt_period = n_batch / n_ubatch;
  2165. opt_params.get_opt_pars = lopt_params.get_opt_pars;
  2166. opt_params.get_opt_pars_ud = lopt_params.get_opt_pars_ud;
  2167. opt_params.optimizer = lopt_params.optimizer_type;
  2168. opt_ctx = ggml_opt_init(opt_params);
  2169. llama_opt_param_filter param_filter = lopt_params.param_filter;
  2170. void * param_filter_ud = lopt_params.param_filter_ud;
  2171. //llama_set_param(model->tok_embd, param_filter, param_filter_ud); // FIXME
  2172. llama_set_param(model->type_embd, param_filter, param_filter_ud);
  2173. llama_set_param(model->pos_embd, param_filter, param_filter_ud);
  2174. llama_set_param(model->tok_norm, param_filter, param_filter_ud);
  2175. llama_set_param(model->tok_norm_b, param_filter, param_filter_ud);
  2176. llama_set_param(model->output_norm, param_filter, param_filter_ud);
  2177. llama_set_param(model->output_norm_b, param_filter, param_filter_ud);
  2178. llama_set_param(model->output, param_filter, param_filter_ud);
  2179. llama_set_param(model->output_b, param_filter, param_filter_ud);
  2180. llama_set_param(model->output_norm_enc, param_filter, param_filter_ud);
  2181. llama_set_param(model->cls, param_filter, param_filter_ud);
  2182. llama_set_param(model->cls_b, param_filter, param_filter_ud);
  2183. llama_set_param(model->cls_out, param_filter, param_filter_ud);
  2184. llama_set_param(model->cls_out_b, param_filter, param_filter_ud);
  2185. for (struct llama_layer & layer : model->layers) {
  2186. for (size_t i = 0; i < sizeof(layer)/sizeof(struct ggml_tensor *); ++i) {
  2187. llama_set_param(reinterpret_cast<struct ggml_tensor **>(&layer)[i], param_filter, param_filter_ud);
  2188. }
  2189. }
  2190. }
  2191. void llama_context::opt_epoch_iter(
  2192. ggml_opt_dataset_t dataset,
  2193. ggml_opt_result_t result,
  2194. const std::vector<llama_token> & tokens,
  2195. const std::vector<llama_token> & labels_sparse,
  2196. llama_batch & batch,
  2197. ggml_opt_epoch_callback callback,
  2198. bool train,
  2199. int64_t idata_in_loop,
  2200. int64_t ndata_in_loop,
  2201. int64_t t_loop_start) {
  2202. GGML_ASSERT(opt_ctx);
  2203. const uint32_t n_ctx = llama_model_n_ctx_train(&model);
  2204. const uint32_t n_batch = std::min(this->n_batch(), n_ctx);
  2205. const uint32_t n_ubatch = std::min(this->n_ubatch(), n_batch);
  2206. memory->clear(true);
  2207. for (uint32_t pos_ctx = 0; pos_ctx < n_ctx; pos_ctx += n_batch) {
  2208. batch.n_tokens = n_batch;
  2209. for (uint32_t pos_batch = 0; pos_batch < n_batch; ++pos_batch) {
  2210. batch.token [pos_batch] = tokens[pos_ctx + pos_batch];
  2211. batch.pos [pos_batch] = pos_ctx + pos_batch;
  2212. batch.n_seq_id[pos_batch] = 1;
  2213. batch.seq_id [pos_batch][0] = 0;
  2214. batch.logits [pos_batch] = true;
  2215. }
  2216. if (!balloc->init(batch, model.vocab, nullptr, model.hparams.n_embd_inp(), cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max, true)) {
  2217. LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
  2218. return;
  2219. }
  2220. const uint32_t n_tokens_all = balloc->get_n_tokens();
  2221. n_queued_tokens += n_tokens_all;
  2222. embd_seq.clear();
  2223. uint32_t n_outputs_all = n_tokens_all;
  2224. auto mctx = memory->init_batch(*balloc, cparams.n_ubatch, true);
  2225. if (!mctx || mctx->get_status() != LLAMA_MEMORY_STATUS_SUCCESS) {
  2226. LLAMA_LOG_ERROR("%s: could not initialize batch\n", __func__);
  2227. break;
  2228. }
  2229. // reserve output buffer
  2230. if (output_reserve(n_outputs_all, balloc->get_batch()) < n_outputs_all) {
  2231. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all);
  2232. GGML_ABORT("TODO: handle this error");
  2233. };
  2234. uint32_t pos_batch = 0;
  2235. do {
  2236. const auto & ubatch = mctx->get_ubatch();
  2237. n_outputs = ubatch.n_tokens;
  2238. if (!mctx->apply()) {
  2239. LLAMA_LOG_ERROR("%s: failed to update the memory context\n", __func__);
  2240. break;
  2241. }
  2242. auto * res = gf_res_prev.get();
  2243. const auto gparams = graph_params(res, ubatch, mctx.get(), LLM_GRAPH_TYPE_DEFAULT);
  2244. res->reset();
  2245. auto * gf = model.build_graph(gparams);
  2246. struct ggml_context * ctx_compute_opt;
  2247. {
  2248. const size_t size_gf = ggml_graph_size(gf);
  2249. const size_t size_meta = 4*size_gf*ggml_tensor_overhead() + 2*ggml_graph_overhead_custom(size_gf, /*grads = */ true);
  2250. struct ggml_init_params params = {
  2251. /*.mem_size =*/ size_meta,
  2252. /*.mem_buffer =*/ nullptr,
  2253. /*.no_alloc =*/ true,
  2254. };
  2255. ctx_compute_opt = ggml_init(params);
  2256. }
  2257. ggml_opt_prepare_alloc(opt_ctx, ctx_compute_opt, gf, res->get_tokens(), res->get_logits());
  2258. ggml_opt_alloc(opt_ctx, train);
  2259. res->set_inputs(&ubatch);
  2260. {
  2261. struct ggml_tensor * labels = ggml_opt_labels(opt_ctx);
  2262. GGML_ASSERT(labels->ne[1] == n_ubatch);
  2263. ggml_set_zero(labels);
  2264. const float onef = 1.0f;
  2265. for (uint32_t pos_ubatch = 0; pos_ubatch < n_ubatch; ++pos_ubatch) {
  2266. const uint32_t ilabel = pos_ctx + pos_batch + pos_ubatch;
  2267. GGML_ASSERT(labels_sparse[ilabel] < labels->ne[0]);
  2268. ggml_backend_tensor_set(labels, &onef, (pos_ubatch*labels->ne[0] + labels_sparse[ilabel])*sizeof(float), sizeof(float));
  2269. }
  2270. }
  2271. ggml_opt_eval(opt_ctx, result);
  2272. if (callback) {
  2273. callback(train, opt_ctx, dataset, result, idata_in_loop + (pos_ctx + pos_batch)/n_ubatch + 1, ndata_in_loop, t_loop_start);
  2274. }
  2275. ggml_free(ctx_compute_opt);
  2276. pos_batch += ubatch.n_tokens;
  2277. } while (mctx->next());
  2278. }
  2279. }
  2280. void llama_context::opt_epoch(
  2281. ggml_opt_dataset_t dataset,
  2282. ggml_opt_result_t result_train,
  2283. ggml_opt_result_t result_eval,
  2284. int64_t idata_split,
  2285. ggml_opt_epoch_callback callback_train,
  2286. ggml_opt_epoch_callback callback_eval) {
  2287. const uint32_t n_ctx = this->n_ctx();
  2288. const uint32_t n_batch = std::min(cparams.n_batch, n_ctx);
  2289. const uint32_t n_ubatch = std::min(cparams.n_ubatch, n_batch);
  2290. const int64_t ndata = ggml_opt_dataset_ndata(dataset);
  2291. GGML_ASSERT(idata_split >= 0);
  2292. GGML_ASSERT(idata_split <= ndata);
  2293. const uint32_t ubatch_per_ctx = n_ctx / n_ubatch;
  2294. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  2295. std::vector<llama_token> tokens(n_ctx);
  2296. std::vector<llama_token> labels_sparse(n_ctx);
  2297. int64_t idata = 0;
  2298. int64_t t_loop_start = ggml_time_us();
  2299. int64_t ndata_in_loop = idata_split*ubatch_per_ctx;
  2300. for (; idata < idata_split; ++idata) {
  2301. constexpr bool train = true;
  2302. const int64_t idata_in_loop = idata*ubatch_per_ctx;
  2303. ggml_opt_dataset_get_batch_host(dataset, tokens.data(), n_ctx*sizeof(llama_token), labels_sparse.data(), idata);
  2304. opt_epoch_iter(dataset, result_train, tokens, labels_sparse, batch,
  2305. callback_train, train, idata_in_loop, ndata_in_loop, t_loop_start);
  2306. }
  2307. t_loop_start = ggml_time_us();
  2308. ndata_in_loop = (ndata - idata_split)*ubatch_per_ctx;
  2309. for (; idata < ndata; ++idata) {
  2310. constexpr bool train = false;
  2311. const int64_t idata_in_loop = (idata - idata_split)*ubatch_per_ctx;
  2312. ggml_opt_dataset_get_batch_host(dataset, tokens.data(), n_ctx*sizeof(llama_token), labels_sparse.data(), idata);
  2313. opt_epoch_iter(dataset, result_eval, tokens, labels_sparse, batch,
  2314. callback_eval, train, idata_in_loop, ndata_in_loop, t_loop_start);
  2315. }
  2316. llama_batch_free(batch);
  2317. }
  2318. //
  2319. // interface implementation
  2320. //
  2321. llama_context_params llama_context_default_params() {
  2322. llama_context_params result = {
  2323. /*.n_ctx =*/ 512,
  2324. /*.n_batch =*/ 2048,
  2325. /*.n_ubatch =*/ 512,
  2326. /*.n_seq_max =*/ 1,
  2327. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  2328. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  2329. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  2330. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  2331. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  2332. /*.flash_attn_type =*/ LLAMA_FLASH_ATTN_TYPE_AUTO,
  2333. /*.rope_freq_base =*/ 0.0f,
  2334. /*.rope_freq_scale =*/ 0.0f,
  2335. /*.yarn_ext_factor =*/ -1.0f,
  2336. /*.yarn_attn_factor =*/ -1.0f,
  2337. /*.yarn_beta_fast =*/ -1.0f,
  2338. /*.yarn_beta_slow =*/ -1.0f,
  2339. /*.yarn_orig_ctx =*/ 0,
  2340. /*.defrag_thold =*/ -1.0f,
  2341. /*.cb_eval =*/ nullptr,
  2342. /*.cb_eval_user_data =*/ nullptr,
  2343. /*.type_k =*/ GGML_TYPE_F16,
  2344. /*.type_v =*/ GGML_TYPE_F16,
  2345. /*.abort_callback =*/ nullptr,
  2346. /*.abort_callback_data =*/ nullptr,
  2347. /*.embeddings =*/ false,
  2348. /*.offload_kqv =*/ true,
  2349. /*.no_perf =*/ true,
  2350. /*.op_offload =*/ true,
  2351. /*.swa_full =*/ true,
  2352. /*.kv_unified =*/ false,
  2353. /*.sampler =*/ nullptr,
  2354. /*.n_sampler =*/ 0,
  2355. };
  2356. return result;
  2357. }
  2358. llama_context * llama_init_from_model(
  2359. llama_model * model,
  2360. llama_context_params params) {
  2361. if (!model) {
  2362. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  2363. return nullptr;
  2364. }
  2365. if (params.n_batch == 0 && params.n_ubatch == 0) {
  2366. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  2367. return nullptr;
  2368. }
  2369. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  2370. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  2371. return nullptr;
  2372. }
  2373. if (params.flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED && model->arch == LLM_ARCH_GROK) {
  2374. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  2375. params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED;
  2376. }
  2377. if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO && ggml_is_quantized(params.type_k)) {
  2378. const uint32_t blck_size = ggml_blck_size(params.type_k);
  2379. if (model->hparams.n_embd_head_k % blck_size != 0) {
  2380. LLAMA_LOG_ERROR("%s: K cache type %s with block size %u does not divide n_embd_head_k=%u\n",
  2381. __func__, ggml_type_name(params.type_k), blck_size, model->hparams.n_embd_head_k);
  2382. return nullptr;
  2383. }
  2384. }
  2385. if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO && ggml_is_quantized(params.type_v)) {
  2386. const uint32_t blck_size = ggml_blck_size(params.type_v);
  2387. if (model->hparams.n_embd_head_v % blck_size != 0) {
  2388. LLAMA_LOG_ERROR("%s: V cache type %s with block size %u does not divide n_embd_head_k=%u\n",
  2389. __func__, ggml_type_name(params.type_v), blck_size, model->hparams.n_embd_head_v);
  2390. return nullptr;
  2391. }
  2392. }
  2393. if (ggml_is_quantized(params.type_v) && params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_DISABLED) {
  2394. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  2395. return nullptr;
  2396. }
  2397. if (params.pooling_type != LLAMA_POOLING_TYPE_UNSPECIFIED &&
  2398. params.pooling_type != model->hparams.pooling_type) {
  2399. //user-specified pooling-type is different from the model default
  2400. LLAMA_LOG_WARN("%s: model default pooling_type is [%d], but [%d] was specified\n", __func__,
  2401. model->hparams.pooling_type, params.pooling_type);
  2402. }
  2403. try {
  2404. auto * ctx = new llama_context(*model, params);
  2405. return ctx;
  2406. } catch (const std::exception & err) {
  2407. LLAMA_LOG_ERROR("%s: failed to initialize the context: %s\n", __func__, err.what());
  2408. }
  2409. return nullptr;
  2410. }
  2411. // deprecated
  2412. llama_context * llama_new_context_with_model(
  2413. llama_model * model,
  2414. llama_context_params params) {
  2415. return llama_init_from_model(model, params);
  2416. }
  2417. void llama_free(llama_context * ctx) {
  2418. delete ctx;
  2419. }
  2420. uint32_t llama_n_ctx(const llama_context * ctx) {
  2421. return ctx->n_ctx();
  2422. }
  2423. uint32_t llama_n_ctx_seq(const llama_context * ctx) {
  2424. return ctx->n_ctx_seq();
  2425. }
  2426. uint32_t llama_n_batch(const llama_context * ctx) {
  2427. return ctx->n_batch();
  2428. }
  2429. uint32_t llama_n_ubatch(const llama_context * ctx) {
  2430. return ctx->n_ubatch();
  2431. }
  2432. uint32_t llama_n_seq_max(const llama_context * ctx) {
  2433. return ctx->n_seq_max();
  2434. }
  2435. const llama_model * llama_get_model(const llama_context * ctx) {
  2436. return &ctx->get_model();
  2437. }
  2438. enum llama_pooling_type llama_pooling_type(const llama_context * ctx) {
  2439. return ctx->pooling_type();
  2440. }
  2441. void llama_attach_threadpool(
  2442. llama_context * ctx,
  2443. ggml_threadpool_t threadpool,
  2444. ggml_threadpool_t threadpool_batch) {
  2445. ctx->attach_threadpool(threadpool, threadpool_batch);
  2446. }
  2447. void llama_detach_threadpool(llama_context * ctx) {
  2448. ctx->detach_threadpool();
  2449. }
  2450. void llama_set_n_threads(llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
  2451. ctx->set_n_threads(n_threads, n_threads_batch);
  2452. }
  2453. int32_t llama_n_threads(llama_context * ctx) {
  2454. return ctx->n_threads();
  2455. }
  2456. int32_t llama_n_threads_batch(llama_context * ctx) {
  2457. return ctx->n_threads_batch();
  2458. }
  2459. void llama_set_abort_callback(llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  2460. ctx->set_abort_callback(abort_callback, abort_callback_data);
  2461. }
  2462. void llama_set_embeddings(llama_context * ctx, bool embeddings) {
  2463. ctx->set_embeddings(embeddings);
  2464. }
  2465. void llama_set_causal_attn(llama_context * ctx, bool causal_attn) {
  2466. ctx->set_causal_attn(causal_attn);
  2467. }
  2468. void llama_set_warmup(llama_context * ctx, bool warmup) {
  2469. ctx->set_warmup(warmup);
  2470. }
  2471. void llama_synchronize(llama_context * ctx) {
  2472. ctx->synchronize();
  2473. }
  2474. float * llama_get_logits(llama_context * ctx) {
  2475. ctx->synchronize();
  2476. return ctx->get_logits();
  2477. }
  2478. float * llama_get_logits_ith(llama_context * ctx, int32_t i) {
  2479. ctx->synchronize();
  2480. float * res = nullptr;
  2481. res = ctx->get_sampled_logits_ith(i);
  2482. if (!res) {
  2483. res = ctx->get_logits_ith(i);
  2484. }
  2485. return res;
  2486. }
  2487. float * llama_get_embeddings(llama_context * ctx) {
  2488. ctx->synchronize();
  2489. return ctx->get_embeddings();
  2490. }
  2491. float * llama_get_embeddings_ith(llama_context * ctx, int32_t i) {
  2492. ctx->synchronize();
  2493. return ctx->get_embeddings_ith(i);
  2494. }
  2495. float * llama_get_embeddings_seq(llama_context * ctx, llama_seq_id seq_id) {
  2496. ctx->synchronize();
  2497. return ctx->get_embeddings_seq(seq_id);
  2498. }
  2499. bool llama_set_sampler(llama_context * ctx, llama_seq_id seq_id, llama_sampler * smpl) {
  2500. return ctx->set_sampler(seq_id, smpl);
  2501. }
  2502. llama_token llama_get_sampled_token_ith(llama_context * ctx, int32_t i) {
  2503. ctx->synchronize();
  2504. return ctx->get_sampled_token_ith(i);
  2505. }
  2506. float * llama_get_sampled_probs_ith(llama_context * ctx, int32_t i) {
  2507. ctx->synchronize();
  2508. return ctx->get_sampled_probs_ith(i);
  2509. }
  2510. float * llama_get_sampled_logits_ith(llama_context * ctx, int32_t i) {
  2511. ctx->synchronize();
  2512. return ctx->get_sampled_logits_ith(i);
  2513. }
  2514. llama_token * llama_get_sampled_candidates_ith(llama_context * ctx, int32_t i) {
  2515. ctx->synchronize();
  2516. return const_cast<llama_token *>(ctx->get_sampled_candidates_ith(i));
  2517. }
  2518. uint32_t llama_get_sampled_candidates_count_ith(llama_context * ctx, int32_t i) {
  2519. ctx->synchronize();
  2520. return static_cast<uint32_t>(ctx->get_sampled_candidates_count(i));
  2521. }
  2522. uint32_t llama_get_sampled_logits_count_ith(llama_context * ctx, int32_t i) {
  2523. ctx->synchronize();
  2524. return static_cast<uint32_t>(ctx->get_sampled_logits_count(i));
  2525. }
  2526. uint32_t llama_get_sampled_probs_count_ith(llama_context * ctx, int32_t i) {
  2527. ctx->synchronize();
  2528. return static_cast<uint32_t>(ctx->get_sampled_probs_count(i));
  2529. }
  2530. // llama adapter API
  2531. int32_t llama_set_adapter_lora(
  2532. llama_context * ctx,
  2533. llama_adapter_lora * adapter,
  2534. float scale) {
  2535. ctx->set_adapter_lora(adapter, scale);
  2536. return 0;
  2537. }
  2538. int32_t llama_rm_adapter_lora(
  2539. llama_context * ctx,
  2540. llama_adapter_lora * adapter) {
  2541. bool res = ctx->rm_adapter_lora(adapter);
  2542. return res ? 0 : -1;
  2543. }
  2544. void llama_clear_adapter_lora(llama_context * ctx) {
  2545. ctx->clear_adapter_lora();
  2546. }
  2547. int32_t llama_apply_adapter_cvec(
  2548. llama_context * ctx,
  2549. const float * data,
  2550. size_t len,
  2551. int32_t n_embd,
  2552. int32_t il_start,
  2553. int32_t il_end) {
  2554. bool res = ctx->apply_adapter_cvec(data, len, n_embd, il_start, il_end);
  2555. return res ? 0 : -1;
  2556. }
  2557. //
  2558. // memory
  2559. //
  2560. llama_memory_t llama_get_memory(const struct llama_context * ctx) {
  2561. return ctx->get_memory();
  2562. }
  2563. void llama_memory_clear(llama_memory_t mem, bool data) {
  2564. if (!mem) {
  2565. return;
  2566. }
  2567. mem->clear(data);
  2568. }
  2569. bool llama_memory_seq_rm(
  2570. llama_memory_t mem,
  2571. llama_seq_id seq_id,
  2572. llama_pos p0,
  2573. llama_pos p1) {
  2574. if (!mem) {
  2575. return true;
  2576. }
  2577. return mem->seq_rm(seq_id, p0, p1);
  2578. }
  2579. void llama_memory_seq_cp(
  2580. llama_memory_t mem,
  2581. llama_seq_id seq_id_src,
  2582. llama_seq_id seq_id_dst,
  2583. llama_pos p0,
  2584. llama_pos p1) {
  2585. if (!mem) {
  2586. return;
  2587. }
  2588. mem->seq_cp(seq_id_src, seq_id_dst, p0, p1);
  2589. }
  2590. void llama_memory_seq_keep(
  2591. llama_memory_t mem,
  2592. llama_seq_id seq_id) {
  2593. if (!mem) {
  2594. return;
  2595. }
  2596. mem->seq_keep(seq_id);
  2597. }
  2598. void llama_memory_seq_add(
  2599. llama_memory_t mem,
  2600. llama_seq_id seq_id,
  2601. llama_pos p0,
  2602. llama_pos p1,
  2603. llama_pos delta) {
  2604. if (!mem) {
  2605. return;
  2606. }
  2607. mem->seq_add(seq_id, p0, p1, delta);
  2608. }
  2609. void llama_memory_seq_div(
  2610. llama_memory_t mem,
  2611. llama_seq_id seq_id,
  2612. llama_pos p0,
  2613. llama_pos p1,
  2614. int d) {
  2615. if (!mem) {
  2616. return;
  2617. }
  2618. mem->seq_div(seq_id, p0, p1, d);
  2619. }
  2620. llama_pos llama_memory_seq_pos_min(
  2621. llama_memory_t mem,
  2622. llama_seq_id seq_id) {
  2623. if (!mem) {
  2624. return -1;
  2625. }
  2626. return mem->seq_pos_min(seq_id);
  2627. }
  2628. llama_pos llama_memory_seq_pos_max(
  2629. llama_memory_t mem,
  2630. llama_seq_id seq_id) {
  2631. if (!mem) {
  2632. return -1;
  2633. }
  2634. return mem->seq_pos_max(seq_id);
  2635. }
  2636. bool llama_memory_can_shift(llama_memory_t mem) {
  2637. if (!mem) {
  2638. return false;
  2639. }
  2640. return mem->get_can_shift();
  2641. }
  2642. // llama state API
  2643. // deprecated
  2644. size_t llama_get_state_size(llama_context * ctx) {
  2645. return llama_state_get_size(ctx);
  2646. }
  2647. // deprecated
  2648. size_t llama_copy_state_data(llama_context * ctx, uint8_t * dst) {
  2649. return llama_state_get_data(ctx, dst, -1);
  2650. }
  2651. // deprecated
  2652. size_t llama_set_state_data(llama_context * ctx, const uint8_t * src) {
  2653. return llama_state_set_data(ctx, src, -1);
  2654. }
  2655. // deprecated
  2656. bool llama_load_session_file(llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  2657. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  2658. }
  2659. // deprecated
  2660. bool llama_save_session_file(llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  2661. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  2662. }
  2663. // Returns the *actual* size of the state.
  2664. // Intended to be used when saving to state to a buffer.
  2665. size_t llama_state_get_size(llama_context * ctx) {
  2666. return ctx->state_get_size();
  2667. }
  2668. size_t llama_state_get_data(llama_context * ctx, uint8_t * dst, size_t size) {
  2669. ctx->synchronize();
  2670. return ctx->state_get_data(dst, size);
  2671. }
  2672. // Sets the state reading from the specified source address
  2673. size_t llama_state_set_data(llama_context * ctx, const uint8_t * src, size_t size) {
  2674. ctx->synchronize();
  2675. return ctx->state_set_data(src, size);
  2676. }
  2677. bool llama_state_load_file(llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  2678. ctx->synchronize();
  2679. try {
  2680. return ctx->state_load_file(path_session, tokens_out, n_token_capacity, n_token_count_out);
  2681. } catch (const std::exception & err) {
  2682. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  2683. return false;
  2684. }
  2685. }
  2686. bool llama_state_save_file(llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  2687. ctx->synchronize();
  2688. try {
  2689. return ctx->state_save_file(path_session, tokens, n_token_count);
  2690. } catch (const std::exception & err) {
  2691. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  2692. return false;
  2693. }
  2694. }
  2695. size_t llama_state_seq_get_size(llama_context * ctx, llama_seq_id seq_id) {
  2696. return llama_state_seq_get_size_ext(ctx, seq_id, 0);
  2697. }
  2698. size_t llama_state_seq_get_data(llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  2699. return llama_state_seq_get_data_ext(ctx, dst, size, seq_id, 0);
  2700. }
  2701. size_t llama_state_seq_set_data(llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id seq_id) {
  2702. return llama_state_seq_set_data_ext(ctx, src, size, seq_id, 0);
  2703. }
  2704. size_t llama_state_seq_get_size_ext(llama_context * ctx, llama_seq_id seq_id, llama_state_seq_flags flags) {
  2705. return ctx->state_seq_get_size(seq_id, flags);
  2706. }
  2707. size_t llama_state_seq_get_data_ext(llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags) {
  2708. ctx->synchronize();
  2709. return ctx->state_seq_get_data(seq_id, dst, size, flags);
  2710. }
  2711. size_t llama_state_seq_set_data_ext(llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags) {
  2712. ctx->synchronize();
  2713. return ctx->state_seq_set_data(seq_id, src, size, flags);
  2714. }
  2715. size_t llama_state_seq_save_file(llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) {
  2716. ctx->synchronize();
  2717. try {
  2718. return ctx->state_seq_save_file(seq_id, filepath, tokens, n_token_count);
  2719. } catch (const std::exception & err) {
  2720. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  2721. return 0;
  2722. }
  2723. }
  2724. size_t llama_state_seq_load_file(llama_context * ctx, const char * filepath, llama_seq_id dest_seq_id, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  2725. ctx->synchronize();
  2726. try {
  2727. return ctx->state_seq_load_file(dest_seq_id, filepath, tokens_out, n_token_capacity, n_token_count_out);
  2728. } catch (const std::exception & err) {
  2729. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  2730. return 0;
  2731. }
  2732. }
  2733. ///
  2734. int32_t llama_encode(
  2735. llama_context * ctx,
  2736. llama_batch batch) {
  2737. const int ret = ctx->encode(batch);
  2738. if (ret != 0) {
  2739. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  2740. }
  2741. return ret;
  2742. }
  2743. int32_t llama_decode(
  2744. llama_context * ctx,
  2745. llama_batch batch) {
  2746. const int ret = ctx->decode(batch);
  2747. if (ret != 0 && ret != 1) {
  2748. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  2749. }
  2750. return ret;
  2751. }
  2752. //
  2753. // perf
  2754. //
  2755. llama_perf_context_data llama_perf_context(const llama_context * ctx) {
  2756. llama_perf_context_data data = {};
  2757. if (ctx == nullptr) {
  2758. return data;
  2759. }
  2760. data = ctx->perf_get_data();
  2761. return data;
  2762. }
  2763. void llama_perf_context_print(const llama_context * ctx) {
  2764. const auto data = llama_perf_context(ctx);
  2765. const double t_end_ms = 1e-3 * ggml_time_us();
  2766. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
  2767. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  2768. __func__, data.t_p_eval_ms, data.n_p_eval, data.t_p_eval_ms / data.n_p_eval, 1e3 / data.t_p_eval_ms * data.n_p_eval);
  2769. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  2770. __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
  2771. LLAMA_LOG_INFO("%s: total time = %10.2f ms / %5d tokens\n", __func__, (t_end_ms - data.t_start_ms), (data.n_p_eval + data.n_eval));
  2772. LLAMA_LOG_INFO("%s: graphs reused = %10d\n", __func__, data.n_reused);
  2773. }
  2774. void llama_perf_context_reset(llama_context * ctx) {
  2775. ctx->perf_reset();
  2776. }
  2777. void llama_memory_breakdown_print(const struct llama_context * ctx) {
  2778. const std::vector<ggml_backend_dev_t> & devices = ctx->get_model().devices;
  2779. std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> memory_breakdown = ctx->memory_breakdown();
  2780. std::vector<std::array<std::string, 9>> table_data;
  2781. table_data.reserve(devices.size());
  2782. const std::string template_header = "%s: | %s | %s %s %s %s %s %s %s |\n";
  2783. const std::string template_gpu = "%s: | %s | %s = %s + (%s = %s + %s + %s) + %s |\n";
  2784. const std::string template_other = "%s: | %s | %s %s %s = %s + %s + %s %s |\n";
  2785. table_data.push_back({template_header, "memory breakdown [MiB]", "total", "free", "self", "model", "context", "compute", "unaccounted"});
  2786. constexpr size_t MiB = 1024 * 1024;
  2787. const std::vector<std::string> desc_prefixes_strip = {"NVIDIA ", "GeForce ", "Tesla ", "AMD ", "Radeon ", "Instinct "};
  2788. // track seen buffer types to avoid double counting:
  2789. std::set<ggml_backend_buffer_type_t> seen_buffer_types;
  2790. // accumulative memory breakdown for each device and for host:
  2791. std::vector<llama_memory_breakdown_data> mb_dev(devices.size());
  2792. llama_memory_breakdown_data mb_host;
  2793. for (const auto & buft_mb : memory_breakdown) {
  2794. ggml_backend_buffer_type_t buft = buft_mb.first;
  2795. const llama_memory_breakdown_data & mb = buft_mb.second;
  2796. if (ggml_backend_buft_is_host(buft)) {
  2797. mb_host.model += mb.model;
  2798. mb_host.context += mb.context;
  2799. mb_host.compute += mb.compute;
  2800. seen_buffer_types.insert(buft);
  2801. continue;
  2802. }
  2803. ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft);
  2804. if (dev) {
  2805. int i_dev = -1;
  2806. for (size_t i = 0; i < devices.size(); i++) {
  2807. if (devices[i] == dev) {
  2808. i_dev = i;
  2809. break;
  2810. }
  2811. }
  2812. if (i_dev != -1) {
  2813. mb_dev[i_dev].model += mb.model;
  2814. mb_dev[i_dev].context += mb.context;
  2815. mb_dev[i_dev].compute += mb.compute;
  2816. seen_buffer_types.insert(buft);
  2817. continue;
  2818. }
  2819. }
  2820. }
  2821. // print memory breakdown for each device:
  2822. for (size_t i = 0; i < devices.size(); i++) {
  2823. ggml_backend_dev_t dev = devices[i];
  2824. llama_memory_breakdown_data mb = mb_dev[i];
  2825. const std::string name = ggml_backend_dev_name(dev);
  2826. std::string desc = ggml_backend_dev_description(dev);
  2827. for (const std::string & prefix : desc_prefixes_strip) {
  2828. if (desc.length() >= prefix.length() && desc.substr(0, prefix.length()) == prefix) {
  2829. desc = desc.substr(prefix.length());
  2830. }
  2831. }
  2832. size_t free, total;
  2833. ggml_backend_dev_memory(dev, &free, &total);
  2834. const size_t self = mb.model + mb.context + mb.compute;
  2835. const size_t unaccounted = total - self - free;
  2836. table_data.push_back({
  2837. template_gpu,
  2838. " - " + name + " (" + desc + ")",
  2839. std::to_string(total / MiB),
  2840. std::to_string(free / MiB),
  2841. std::to_string(self / MiB),
  2842. std::to_string(mb.model / MiB),
  2843. std::to_string(mb.context / MiB),
  2844. std::to_string(mb.compute / MiB),
  2845. std::to_string(unaccounted / MiB)});
  2846. }
  2847. // print memory breakdown for host:
  2848. {
  2849. const size_t self = mb_host.model + mb_host.context + mb_host.compute;
  2850. table_data.push_back({
  2851. template_other,
  2852. " - Host",
  2853. "", // total
  2854. "", // free
  2855. std::to_string(self / MiB),
  2856. std::to_string(mb_host.model / MiB),
  2857. std::to_string(mb_host.context / MiB),
  2858. std::to_string(mb_host.compute / MiB),
  2859. ""}); // unaccounted
  2860. }
  2861. // print memory breakdown for all remaining buffer types:
  2862. for (const auto & buft_mb : memory_breakdown) {
  2863. ggml_backend_buffer_type_t buft = buft_mb.first;
  2864. const llama_memory_breakdown_data & mb = buft_mb.second;
  2865. if (seen_buffer_types.count(buft) == 1) {
  2866. continue;
  2867. }
  2868. const std::string name = ggml_backend_buft_name(buft);
  2869. const size_t self = mb.model + mb.context + mb.compute;
  2870. table_data.push_back({
  2871. template_other,
  2872. " - " + name,
  2873. "", // total
  2874. "", // free
  2875. std::to_string(self / MiB),
  2876. std::to_string(mb.model / MiB),
  2877. std::to_string(mb.context / MiB),
  2878. std::to_string(mb.compute / MiB),
  2879. ""}); // unaccounted
  2880. seen_buffer_types.insert(buft);
  2881. }
  2882. for (size_t j = 1; j < table_data[0].size(); j++) {
  2883. size_t max_len = 0;
  2884. for (const auto & td : table_data) {
  2885. max_len = std::max(max_len, td[j].length());
  2886. }
  2887. for (auto & td : table_data) {
  2888. td[j].insert(j == 1 ? td[j].length() : 0, max_len - td[j].length(), ' ');
  2889. }
  2890. }
  2891. for (const auto & td : table_data) {
  2892. LLAMA_LOG_INFO(td[0].c_str(),
  2893. __func__, td[1].c_str(), td[2].c_str(), td[3].c_str(), td[4].c_str(), td[5].c_str(),
  2894. td[6].c_str(), td[7].c_str(), td[8].c_str());
  2895. }
  2896. }
  2897. //
  2898. // training
  2899. //
  2900. bool llama_opt_param_filter_all(const struct ggml_tensor * tensor, void * userdata) {
  2901. GGML_UNUSED(tensor);
  2902. GGML_UNUSED(userdata);
  2903. return true;
  2904. }
  2905. void llama_opt_init(struct llama_context * ctx, struct llama_model * model, struct llama_opt_params lopt_params) {
  2906. ctx->opt_init(model, lopt_params);
  2907. }
  2908. void llama_opt_epoch(
  2909. struct llama_context * ctx,
  2910. ggml_opt_dataset_t dataset,
  2911. ggml_opt_result_t result_train,
  2912. ggml_opt_result_t result_eval,
  2913. int64_t idata_split,
  2914. ggml_opt_epoch_callback callback_train,
  2915. ggml_opt_epoch_callback callback_eval) {
  2916. ctx->opt_epoch(
  2917. dataset,
  2918. result_train,
  2919. result_eval,
  2920. idata_split,
  2921. callback_train,
  2922. callback_eval);
  2923. }