llama-context.cpp 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940
  1. #include "llama-context.h"
  2. #include "llama-impl.h"
  3. #include "llama-batch.h"
  4. #include "llama-io.h"
  5. #include "llama-memory.h"
  6. #include "llama-mmap.h"
  7. #include "llama-model.h"
  8. #include <cinttypes>
  9. #include <cstring>
  10. #include <limits>
  11. #include <stdexcept>
  12. //
  13. // llama_context
  14. //
  15. llama_context::llama_context(
  16. const llama_model & model,
  17. llama_context_params params) :
  18. model(model),
  19. balloc(std::make_unique<llama_batch_allocr>(model.hparams.n_pos_per_embd())) {
  20. LLAMA_LOG_INFO("%s: constructing llama_context\n", __func__);
  21. t_start_us = model.t_start_us;
  22. t_load_us = model.t_load_us;
  23. const auto & hparams = model.hparams;
  24. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  25. if (cparams.n_seq_max > LLAMA_MAX_SEQ) {
  26. throw std::runtime_error("n_seq_max must be <= " + std::to_string(LLAMA_MAX_SEQ));
  27. }
  28. cparams.n_threads = params.n_threads;
  29. cparams.n_threads_batch = params.n_threads_batch;
  30. cparams.yarn_ext_factor = params.yarn_ext_factor;
  31. cparams.yarn_attn_factor = params.yarn_attn_factor;
  32. cparams.yarn_beta_fast = params.yarn_beta_fast;
  33. cparams.yarn_beta_slow = params.yarn_beta_slow;
  34. cparams.defrag_thold = params.defrag_thold;
  35. cparams.embeddings = params.embeddings;
  36. cparams.offload_kqv = params.offload_kqv;
  37. cparams.flash_attn = params.flash_attn;
  38. cparams.no_perf = params.no_perf;
  39. cparams.pooling_type = params.pooling_type;
  40. cparams.warmup = false;
  41. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  42. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  43. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  44. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  45. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  46. hparams.n_ctx_train;
  47. cparams.cb_eval = params.cb_eval;
  48. cparams.cb_eval_user_data = params.cb_eval_user_data;
  49. auto rope_scaling_type = params.rope_scaling_type;
  50. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  51. rope_scaling_type = hparams.rope_scaling_type_train;
  52. }
  53. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  54. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  55. }
  56. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  57. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  58. }
  59. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  60. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  61. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  62. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  63. } else {
  64. cparams.pooling_type = hparams.pooling_type;
  65. }
  66. }
  67. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  68. cparams.causal_attn = hparams.causal_attn;
  69. } else {
  70. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  71. }
  72. // with causal attention, the batch size is limited by the context size
  73. cparams.n_batch = cparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  74. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  75. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  76. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  77. // TODO: this padding is not needed for the cache-less context so we should probably move it to llama_context_kv_self
  78. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  79. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  80. cparams.n_batch = GGML_KQ_MASK_PAD;
  81. }
  82. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  83. cparams.op_offload = params.op_offload;
  84. cparams.kv_unified = params.kv_unified;
  85. {
  86. const char * LLAMA_SET_ROWS = getenv("LLAMA_SET_ROWS");
  87. supports_set_rows = LLAMA_SET_ROWS ? (atoi(LLAMA_SET_ROWS) != 0) : supports_set_rows;
  88. if (!supports_set_rows && !cparams.kv_unified) {
  89. LLAMA_LOG_WARN("%s: non-unified KV cache requires ggml_set_rows() - forcing unified KV cache\n", __func__);
  90. cparams.kv_unified = true;
  91. }
  92. }
  93. {
  94. const char * LLAMA_GRAPH_REUSE_DISABLE = getenv("LLAMA_GRAPH_REUSE_DISABLE");
  95. graph_reuse_disable = LLAMA_GRAPH_REUSE_DISABLE ? (atoi(LLAMA_GRAPH_REUSE_DISABLE) != 0) : graph_reuse_disable;
  96. if (graph_reuse_disable) {
  97. LLAMA_LOG_WARN("%s: graph reuse disabled\n", __func__);
  98. }
  99. }
  100. const uint32_t n_ctx_per_seq = cparams.n_ctx / cparams.n_seq_max;
  101. LLAMA_LOG_INFO("%s: n_seq_max = %u\n", __func__, cparams.n_seq_max);
  102. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  103. LLAMA_LOG_INFO("%s: n_ctx_per_seq = %u\n", __func__, n_ctx_per_seq);
  104. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  105. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  106. LLAMA_LOG_INFO("%s: causal_attn = %d\n", __func__, cparams.causal_attn);
  107. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  108. LLAMA_LOG_INFO("%s: kv_unified = %s\n", __func__, cparams.kv_unified ? "true" : "false");
  109. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  110. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  111. if (n_ctx_per_seq < hparams.n_ctx_train) {
  112. LLAMA_LOG_WARN("%s: n_ctx_per_seq (%u) < n_ctx_train (%u) -- the full capacity of the model will not be utilized\n",
  113. __func__, n_ctx_per_seq, hparams.n_ctx_train);
  114. }
  115. if (n_ctx_per_seq > hparams.n_ctx_train) {
  116. LLAMA_LOG_WARN("%s: n_ctx_per_seq (%u) > n_ctx_train (%u) -- possible training context overflow\n",
  117. __func__, n_ctx_per_seq, hparams.n_ctx_train);
  118. }
  119. if (!params.swa_full && cparams.n_seq_max > 1 && hparams.is_swa_any()) {
  120. LLAMA_LOG_WARN("%s: requested n_seq_max (%u) > 1, but swa_full is not enabled -- performance may be degraded: %s\n",
  121. __func__, cparams.n_seq_max, "https://github.com/ggml-org/llama.cpp/pull/13845#issuecomment-2924800573");
  122. }
  123. if (!hparams.vocab_only) {
  124. // GPU backends
  125. for (auto * dev : model.devices) {
  126. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  127. if (backend == nullptr) {
  128. throw std::runtime_error(format("failed to initialize %s backend", ggml_backend_dev_name(dev)));
  129. }
  130. backends.emplace_back(backend);
  131. }
  132. // add ACCEL backends (such as BLAS)
  133. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  134. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  135. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
  136. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  137. if (backend == nullptr) {
  138. throw std::runtime_error(format("failed to initialize %s backend", ggml_backend_dev_name(dev)));
  139. }
  140. backends.emplace_back(backend);
  141. }
  142. }
  143. // add CPU backend
  144. backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
  145. if (backend_cpu == nullptr) {
  146. throw std::runtime_error("failed to initialize CPU backend");
  147. }
  148. backends.emplace_back(backend_cpu);
  149. // create a list of the set_n_threads functions in the backends
  150. for (auto & backend : backends) {
  151. ggml_backend_dev_t dev = ggml_backend_get_device(backend.get());
  152. ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
  153. if (reg) {
  154. 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");
  155. if (ggml_backend_set_n_threads_fn) {
  156. set_n_threads_fns.emplace_back(backend.get(), ggml_backend_set_n_threads_fn);
  157. }
  158. }
  159. }
  160. llama_set_abort_callback(this, params.abort_callback, params.abort_callback_data);
  161. // graph outputs buffer
  162. {
  163. // resized during inference when a batch uses more outputs
  164. if ((uint32_t) output_reserve(params.n_seq_max) < params.n_seq_max) {
  165. throw std::runtime_error("failed to reserve initial output buffer");
  166. }
  167. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  168. ggml_backend_buffer_name (buf_output.get()),
  169. ggml_backend_buffer_get_size(buf_output.get()) / 1024.0 / 1024.0);
  170. }
  171. }
  172. // init the memory module
  173. if (!hparams.vocab_only) {
  174. llama_memory_params params_mem = {
  175. /*.type_k =*/ params.type_k,
  176. /*.type_v =*/ params.type_v,
  177. /*.swa_full =*/ params.swa_full,
  178. };
  179. memory.reset(model.create_memory(params_mem, cparams));
  180. }
  181. // init backends
  182. if (!hparams.vocab_only) {
  183. LLAMA_LOG_DEBUG("%s: enumerating backends\n", __func__);
  184. backend_buft.clear();
  185. backend_ptrs.clear();
  186. for (auto & backend : backends) {
  187. auto * buft = ggml_backend_get_default_buffer_type(backend.get());
  188. auto backend_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
  189. if (backend_type == GGML_BACKEND_DEVICE_TYPE_CPU && !model.devices.empty()) {
  190. // use the host buffer of the first device CPU for faster transfer of the intermediate state
  191. auto * dev = model.devices[0];
  192. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  193. if (host_buft) {
  194. buft = host_buft;
  195. }
  196. }
  197. backend_buft.push_back(buft);
  198. backend_ptrs.push_back(backend.get());
  199. }
  200. LLAMA_LOG_DEBUG("%s: backend_ptrs.size() = %zu\n", __func__, backend_ptrs.size());
  201. const size_t max_nodes = this->graph_max_nodes();
  202. LLAMA_LOG_DEBUG("%s: max_nodes = %zu\n", __func__, max_nodes);
  203. gf_res_prev.reset(new llm_graph_result(max_nodes));
  204. gf_res_reserve.reset(new llm_graph_result(max_nodes));
  205. // TODO: move these checks to ggml_backend_sched
  206. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  207. bool pipeline_parallel =
  208. model.n_devices() > 1 &&
  209. model.params.n_gpu_layers > (int) model.hparams.n_layer &&
  210. model.params.split_mode == LLAMA_SPLIT_MODE_LAYER &&
  211. cparams.offload_kqv &&
  212. !model.has_tensor_overrides();
  213. // pipeline parallelism requires support for async compute and events in all devices
  214. if (pipeline_parallel) {
  215. for (auto & backend : backends) {
  216. auto dev_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
  217. if (dev_type == GGML_BACKEND_DEVICE_TYPE_CPU) {
  218. // ignore CPU backend
  219. continue;
  220. }
  221. auto * dev = ggml_backend_get_device(backend.get());
  222. ggml_backend_dev_props props;
  223. ggml_backend_dev_get_props(dev, &props);
  224. if (!props.caps.async || !props.caps.events) {
  225. // device does not support async compute or events
  226. pipeline_parallel = false;
  227. break;
  228. }
  229. }
  230. }
  231. sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), max_nodes, pipeline_parallel, cparams.op_offload));
  232. if (pipeline_parallel) {
  233. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(sched.get()));
  234. }
  235. }
  236. // reserve worst-case graph
  237. if (!hparams.vocab_only && memory) {
  238. const uint32_t n_seqs = cparams.kv_unified ? 1 : cparams.n_seq_max;
  239. const uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  240. LLAMA_LOG_DEBUG("%s: worst-case: n_tokens = %d, n_seqs = %d, n_outputs = %d\n", __func__, n_tokens, n_seqs, n_outputs);
  241. int n_splits_pp = -1;
  242. int n_nodes_pp = -1;
  243. int n_splits_tg = -1;
  244. int n_nodes_tg = -1;
  245. // simulate full KV cache
  246. const auto mctx = memory->init_full();
  247. if (!mctx) {
  248. throw std::runtime_error("failed to initialize KV cache");
  249. }
  250. cross.v_embd.clear();
  251. // reserve pp (prompt processing) graph first so that buffers are only allocated once
  252. {
  253. auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get());
  254. if (!gf) {
  255. throw std::runtime_error("failed to allocate compute pp buffers");
  256. }
  257. n_splits_pp = ggml_backend_sched_get_n_splits(sched.get());
  258. n_nodes_pp = ggml_graph_n_nodes(gf);
  259. }
  260. // reserve with tg (token generation) graph to get the number of splits and nodes
  261. {
  262. auto * gf = graph_reserve(n_seqs, n_seqs, n_seqs, mctx.get());
  263. if (!gf) {
  264. throw std::runtime_error("failed to allocate compute tg buffers");
  265. }
  266. n_splits_tg = ggml_backend_sched_get_n_splits(sched.get());
  267. n_nodes_tg = ggml_graph_n_nodes(gf);
  268. }
  269. // reserve again with pp graph to avoid ggml-alloc reallocations during inference
  270. {
  271. // TODO: not sure if the following graph would be worster case for multi-stream KV caches:
  272. //
  273. // auto * gf = graph_reserve(n_tokens, 1, n_tokens, mctx.get());
  274. //
  275. auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get());
  276. if (!gf) {
  277. throw std::runtime_error("failed to allocate compute pp buffers");
  278. }
  279. }
  280. for (size_t i = 0; i < backend_ptrs.size(); ++i) {
  281. ggml_backend_t backend = backend_ptrs[i];
  282. ggml_backend_buffer_type_t buft = backend_buft[i];
  283. size_t size = ggml_backend_sched_get_buffer_size(sched.get(), backend);
  284. if (size > 1) {
  285. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  286. ggml_backend_buft_name(buft),
  287. size / 1024.0 / 1024.0);
  288. }
  289. }
  290. if (n_nodes_pp == n_nodes_tg) {
  291. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, n_nodes_pp);
  292. } else {
  293. LLAMA_LOG_INFO("%s: graph nodes = %d (with bs=%d), %d (with bs=1)\n", __func__, n_nodes_pp, n_tokens, n_nodes_tg);
  294. }
  295. if (n_splits_pp == n_splits_tg) {
  296. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits_pp);
  297. } else {
  298. LLAMA_LOG_INFO("%s: graph splits = %d (with bs=%d), %d (with bs=1)\n", __func__, n_splits_pp, n_tokens, n_splits_tg);
  299. }
  300. }
  301. }
  302. llama_context::~llama_context() {
  303. ggml_opt_free(opt_ctx);
  304. }
  305. void llama_context::synchronize() {
  306. ggml_backend_sched_synchronize(sched.get());
  307. // FIXME: if multiple single tokens are evaluated without a synchronization,
  308. // the stats will be added to the prompt evaluation stats
  309. // this should only happen when using batch size 1 to evaluate a batch
  310. // add the evaluation to the stats
  311. if (n_queued_tokens == 1) {
  312. if (!cparams.no_perf) {
  313. t_eval_us += ggml_time_us() - t_compute_start_us;
  314. }
  315. n_eval++;
  316. } else if (n_queued_tokens > 1) {
  317. if (!cparams.no_perf) {
  318. t_p_eval_us += ggml_time_us() - t_compute_start_us;
  319. }
  320. n_p_eval += n_queued_tokens;
  321. }
  322. // get a more accurate load time, upon first eval
  323. if (n_queued_tokens > 0 && !has_evaluated_once) {
  324. t_load_us = ggml_time_us() - t_start_us;
  325. has_evaluated_once = true;
  326. }
  327. n_queued_tokens = 0;
  328. t_compute_start_us = 0;
  329. }
  330. const llama_model & llama_context::get_model() const {
  331. return model;
  332. }
  333. const llama_cparams & llama_context::get_cparams() const {
  334. return cparams;
  335. }
  336. ggml_backend_sched_t llama_context::get_sched() const {
  337. return sched.get();
  338. }
  339. uint32_t llama_context::n_ctx() const {
  340. return cparams.n_ctx;
  341. }
  342. uint32_t llama_context::n_ctx_per_seq() const {
  343. return cparams.n_ctx / cparams.n_seq_max;
  344. }
  345. uint32_t llama_context::n_batch() const {
  346. return cparams.n_batch;
  347. }
  348. uint32_t llama_context::n_ubatch() const {
  349. return cparams.n_ubatch;
  350. }
  351. uint32_t llama_context::n_seq_max() const {
  352. return cparams.n_seq_max;
  353. }
  354. uint32_t llama_context::n_threads() const {
  355. return cparams.n_threads;
  356. }
  357. uint32_t llama_context::n_threads_batch() const {
  358. return cparams.n_threads_batch;
  359. }
  360. llama_memory_t llama_context::get_memory() const {
  361. return memory.get();
  362. }
  363. // deprecated
  364. void llama_context::kv_self_defrag_sched() {
  365. if (!memory) {
  366. return;
  367. }
  368. memory_force_optimize = true;
  369. }
  370. // deprecated
  371. bool llama_context::kv_self_update(bool optimize) {
  372. if (!memory) {
  373. return false;
  374. }
  375. {
  376. // TODO: remove in the future
  377. optimize |= memory_force_optimize;
  378. memory_force_optimize = false;
  379. const auto mctx = memory->init_update(this, optimize);
  380. switch (mctx->get_status()) {
  381. case LLAMA_MEMORY_STATUS_SUCCESS:
  382. {
  383. // noop
  384. } break;
  385. case LLAMA_MEMORY_STATUS_NO_UPDATE:
  386. {
  387. // no updates need to be performed
  388. return false;
  389. }
  390. case LLAMA_MEMORY_STATUS_FAILED_PREPARE:
  391. case LLAMA_MEMORY_STATUS_FAILED_COMPUTE:
  392. {
  393. LLAMA_LOG_ERROR("%s: failed to prepare memory update\n", __func__);
  394. return false;
  395. }
  396. }
  397. // reset the previous graph result to make sure that it won't be reused
  398. // TODO: change the mctx->apply() to return information if a graph reserve is needed
  399. // reset the graph result only if the memory module did reset the scheduler
  400. gf_res_prev->reset();
  401. if (!mctx->apply()) {
  402. LLAMA_LOG_ERROR("%s: failed to apply memory update\n", __func__);
  403. }
  404. }
  405. // if the memory module did any computation, we have to reserve a new worst-case graph
  406. {
  407. const auto mctx = memory->init_full();
  408. if (!mctx) {
  409. throw std::runtime_error("failed to initialize memory context");
  410. }
  411. const uint32_t n_seqs = cparams.kv_unified ? 1 : cparams.n_seq_max;
  412. const uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  413. auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get());
  414. if (!gf) {
  415. LLAMA_LOG_ERROR("%s: failed to reserve graph after the memory update\n", __func__);
  416. }
  417. }
  418. return true;
  419. }
  420. enum llama_pooling_type llama_context::pooling_type() const {
  421. return cparams.pooling_type;
  422. }
  423. float * llama_context::get_logits() {
  424. output_reorder();
  425. return logits;
  426. }
  427. float * llama_context::get_logits_ith(int32_t i) {
  428. int64_t j = -1;
  429. output_reorder();
  430. try {
  431. if (logits == nullptr) {
  432. throw std::runtime_error("no logits");
  433. }
  434. if (i < 0) {
  435. j = n_outputs + i;
  436. if (j < 0) {
  437. throw std::runtime_error(format("negative index out of range [0, %d)", n_outputs));
  438. }
  439. } else if ((size_t) i >= output_ids.size()) {
  440. throw std::runtime_error(format("out of range [0, %zu)", output_ids.size()));
  441. } else {
  442. j = output_ids[i];
  443. }
  444. if (j < 0) {
  445. throw std::runtime_error(format("batch.logits[%d] != true", i));
  446. }
  447. if (j >= n_outputs) {
  448. // This should not happen
  449. throw std::runtime_error(format("corrupt output buffer (j=%" PRId64 ", n_outputs=%d)", j, n_outputs));
  450. }
  451. return logits + j*model.vocab.n_tokens();
  452. } catch (const std::exception & err) {
  453. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  454. #ifndef NDEBUG
  455. GGML_ABORT("fatal error");
  456. #else
  457. return nullptr;
  458. #endif
  459. }
  460. }
  461. float * llama_context::get_embeddings() {
  462. output_reorder();
  463. return embd;
  464. }
  465. float * llama_context::get_embeddings_ith(int32_t i) {
  466. int64_t j = -1;
  467. output_reorder();
  468. try {
  469. if (embd == nullptr) {
  470. throw std::runtime_error("no embeddings");
  471. }
  472. if (i < 0) {
  473. j = n_outputs + i;
  474. if (j < 0) {
  475. throw std::runtime_error(format("negative index out of range [0, %d)", n_outputs));
  476. }
  477. } else if ((size_t) i >= output_ids.size()) {
  478. throw std::runtime_error(format("out of range [0, %zu)", output_ids.size()));
  479. } else {
  480. j = output_ids[i];
  481. }
  482. if (j < 0) {
  483. throw std::runtime_error(format("batch.logits[%d] != true", i));
  484. }
  485. if (j >= n_outputs) {
  486. // This should not happen
  487. throw std::runtime_error(format("corrupt output buffer (j=%" PRId64 ", n_outputs=%d)", j, n_outputs));
  488. }
  489. return embd + j*model.hparams.n_embd;
  490. } catch (const std::exception & err) {
  491. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  492. #ifndef NDEBUG
  493. GGML_ABORT("fatal error");
  494. #else
  495. return nullptr;
  496. #endif
  497. }
  498. }
  499. float * llama_context::get_embeddings_seq(llama_seq_id seq_id) {
  500. auto it = embd_seq.find(seq_id);
  501. if (it == embd_seq.end()) {
  502. return nullptr;
  503. }
  504. return it->second.data();
  505. }
  506. void llama_context::attach_threadpool(
  507. ggml_threadpool_t threadpool,
  508. ggml_threadpool_t threadpool_batch) {
  509. LLAMA_LOG_DEBUG("%s: call\n", __func__);
  510. this->threadpool = threadpool;
  511. this->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
  512. }
  513. void llama_context::detach_threadpool() {
  514. LLAMA_LOG_DEBUG("%s: call\n", __func__);
  515. this->threadpool = nullptr;
  516. this->threadpool_batch = nullptr;
  517. }
  518. void llama_context::set_n_threads(int32_t n_threads, int32_t n_threads_batch) {
  519. LLAMA_LOG_DEBUG("%s: n_threads = %d, n_threads_batch = %d\n", __func__, n_threads, n_threads_batch);
  520. cparams.n_threads = n_threads;
  521. cparams.n_threads_batch = n_threads_batch;
  522. }
  523. void llama_context::set_abort_callback(bool (*abort_callback)(void * data), void * abort_callback_data) {
  524. LLAMA_LOG_DEBUG("%s: call\n", __func__);
  525. this->abort_callback = abort_callback;
  526. this->abort_callback_data = abort_callback_data;
  527. for (auto & backend : backends) {
  528. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend.get()));
  529. auto * set_abort_callback_fn = (ggml_backend_set_abort_callback_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_abort_callback");
  530. if (set_abort_callback_fn) {
  531. set_abort_callback_fn(backend.get(), this->abort_callback, this->abort_callback_data);
  532. }
  533. }
  534. }
  535. void llama_context::set_embeddings(bool value) {
  536. LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
  537. cparams.embeddings = value;
  538. }
  539. void llama_context::set_causal_attn(bool value) {
  540. LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
  541. cparams.causal_attn = value;
  542. }
  543. void llama_context::set_warmup(bool value) {
  544. LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
  545. cparams.warmup = value;
  546. }
  547. void llama_context::set_adapter_lora(
  548. llama_adapter_lora * adapter,
  549. float scale) {
  550. LLAMA_LOG_DEBUG("%s: adapter = %p, scale = %f\n", __func__, (void *) adapter, scale);
  551. loras[adapter] = scale;
  552. }
  553. bool llama_context::rm_adapter_lora(
  554. llama_adapter_lora * adapter) {
  555. LLAMA_LOG_DEBUG("%s: adapter = %p\n", __func__, (void *) adapter);
  556. auto pos = loras.find(adapter);
  557. if (pos != loras.end()) {
  558. loras.erase(pos);
  559. return true;
  560. }
  561. return false;
  562. }
  563. void llama_context::clear_adapter_lora() {
  564. LLAMA_LOG_DEBUG("%s: call\n", __func__);
  565. loras.clear();
  566. }
  567. bool llama_context::apply_adapter_cvec(
  568. const float * data,
  569. size_t len,
  570. int32_t n_embd,
  571. int32_t il_start,
  572. int32_t il_end) {
  573. LLAMA_LOG_DEBUG("%s: il_start = %d, il_end = %d\n", __func__, il_start, il_end);
  574. return cvec.apply(model, data, len, n_embd, il_start, il_end);
  575. }
  576. llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, llm_graph_type gtype, llama_memory_context_i * mctx, ggml_status & ret) {
  577. if (mctx && !mctx->apply()) {
  578. LLAMA_LOG_ERROR("%s: failed to apply memory context\n", __func__);
  579. ret = GGML_STATUS_FAILED;
  580. return nullptr;
  581. }
  582. auto * res = gf_res_prev.get();
  583. auto * gf = res->get_gf();
  584. // the new graph parameters
  585. // in order to correctly reuse a graph, it's full topology has to be uniquely determined by these parameters
  586. const auto gparams = graph_params(res, ubatch, mctx, gtype);
  587. if (!graph_reuse_disable && res->can_reuse(gparams)) {
  588. //LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__);
  589. n_reused++;
  590. } else {
  591. res->reset();
  592. ggml_backend_sched_reset(sched.get());
  593. ggml_backend_sched_set_eval_callback(sched.get(), cparams.cb_eval, cparams.cb_eval_user_data);
  594. //const auto t_start_us = ggml_time_us();
  595. gf = model.build_graph(gparams);
  596. //LLAMA_LOG_INFO("graph build time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0);
  597. if (!gf) {
  598. LLAMA_LOG_ERROR("%s: failed to initialize graph\n", __func__);
  599. ret = GGML_STATUS_FAILED;
  600. return nullptr;
  601. }
  602. if (!ggml_backend_sched_alloc_graph(sched.get(), gf)) {
  603. LLAMA_LOG_ERROR("%s: failed to allocate graph\n", __func__);
  604. ret = GGML_STATUS_ALLOC_FAILED;
  605. return nullptr;
  606. }
  607. }
  608. // set the input data for the input tensors
  609. {
  610. //const auto t_start_us = ggml_time_us();
  611. res->set_inputs(&ubatch);
  612. //LLAMA_LOG_INFO("graph set inputs time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0);
  613. }
  614. const auto status = graph_compute(res->get_gf(), ubatch.n_tokens > 1);
  615. if (status != GGML_STATUS_SUCCESS) {
  616. LLAMA_LOG_ERROR("%s: failed to compute graph, compute status: %d\n", __func__, status);
  617. ret = status;
  618. return nullptr;
  619. }
  620. ret = GGML_STATUS_SUCCESS;
  621. return res;
  622. }
  623. int llama_context::encode(const llama_batch & batch_inp) {
  624. GGML_ASSERT((!batch_inp.token && batch_inp.embd) || (batch_inp.token && !batch_inp.embd)); // NOLINT
  625. if (batch_inp.n_tokens == 0) {
  626. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  627. return -1;
  628. }
  629. const auto & hparams = model.hparams;
  630. const int64_t n_embd = hparams.n_embd;
  631. const int64_t n_vocab = model.vocab.n_tokens();
  632. // note: during encode, we always pass the full sequence starting from pos = 0
  633. if (!balloc->init(batch_inp, model.vocab, nullptr, n_embd, cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max, true)) {
  634. LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
  635. return -1;
  636. }
  637. const uint32_t n_tokens = balloc->get_n_tokens();
  638. // [TAG_NO_CACHE_PAD]
  639. // TODO: add new split mode where we pad the input sequences so that ubatch.equal_seqs == true
  640. const llama_ubatch ubatch = balloc->split_simple(n_tokens);
  641. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  642. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  643. if (t_compute_start_us == 0) {
  644. t_compute_start_us = ggml_time_us();
  645. }
  646. // TODO: this clear of the buffer can easily be forgotten - need something better
  647. embd_seq.clear();
  648. n_queued_tokens += n_tokens;
  649. // reserve output buffer
  650. if (output_reserve(n_tokens) < n_tokens) {
  651. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  652. return -2;
  653. };
  654. for (uint32_t i = 0; i < n_tokens; ++i) {
  655. output_ids[i] = i;
  656. }
  657. n_outputs = n_tokens;
  658. const auto causal_attn_org = cparams.causal_attn;
  659. // always use non-causal attention for encoder graphs
  660. // TODO: this is a tmp solution until we have a proper way to support enc-dec models
  661. // ref: https://github.com/ggml-org/llama.cpp/pull/12181#issuecomment-2730451223
  662. cparams.causal_attn = false;
  663. ggml_status status;
  664. const auto * res = process_ubatch(ubatch, LLM_GRAPH_TYPE_ENCODER, nullptr, status);
  665. cparams.causal_attn = causal_attn_org;
  666. if (!res) {
  667. switch (status) {
  668. case GGML_STATUS_ABORTED: return 2;
  669. case GGML_STATUS_ALLOC_FAILED: return -2;
  670. case GGML_STATUS_FAILED: return -3;
  671. case GGML_STATUS_SUCCESS: GGML_ABORT("should not happen");
  672. }
  673. }
  674. auto * t_logits = res->get_logits();
  675. auto * t_embd = res->get_embd_pooled() ? res->get_embd_pooled() : res->get_embd();
  676. // extract logits
  677. if (logits && t_logits) {
  678. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits);
  679. GGML_ASSERT(backend_res != nullptr);
  680. GGML_ASSERT(logits != nullptr);
  681. ggml_backend_tensor_get_async(backend_res, t_logits, logits, 0, n_tokens*n_vocab*sizeof(float));
  682. }
  683. // extract embeddings
  684. if (embd && t_embd) {
  685. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd);
  686. GGML_ASSERT(backend_embd != nullptr);
  687. switch (cparams.pooling_type) {
  688. case LLAMA_POOLING_TYPE_NONE:
  689. {
  690. // extract token embeddings
  691. GGML_ASSERT(embd != nullptr);
  692. GGML_ASSERT(n_tokens*n_embd <= (int64_t) embd_size);
  693. ggml_backend_tensor_get_async(backend_embd, t_embd, embd, 0, n_tokens*n_embd*sizeof(float));
  694. } break;
  695. case LLAMA_POOLING_TYPE_MEAN:
  696. case LLAMA_POOLING_TYPE_CLS:
  697. case LLAMA_POOLING_TYPE_LAST:
  698. {
  699. // extract sequence embeddings
  700. auto & embd_seq_out = embd_seq;
  701. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  702. const llama_seq_id seq_id = ubatch.seq_id_unq[s];
  703. const int32_t seq_idx = ubatch.seq_idx[seq_id];
  704. embd_seq_out[seq_id].resize(n_embd);
  705. 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));
  706. }
  707. } break;
  708. case LLAMA_POOLING_TYPE_RANK:
  709. {
  710. // extract the rerank score - n_cls_out floats per sequence
  711. auto & embd_seq_out = embd_seq;
  712. const uint32_t n_cls_out = hparams.n_cls_out;
  713. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  714. const llama_seq_id seq_id = ubatch.seq_id_unq[s];
  715. const int32_t seq_idx = ubatch.seq_idx[seq_id];
  716. embd_seq_out[seq_id].resize(n_cls_out);
  717. 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));
  718. }
  719. } break;
  720. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  721. {
  722. GGML_ABORT("unknown pooling type");
  723. }
  724. }
  725. }
  726. if (!supports_set_rows) {
  727. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  728. // overlap with device computation.
  729. ggml_backend_sched_reset(sched.get());
  730. }
  731. // TODO: hacky solution
  732. if (model.arch == LLM_ARCH_T5 && t_embd) {
  733. //cross.t_embd = t_embd;
  734. synchronize();
  735. cross.n_embd = t_embd->ne[0];
  736. cross.n_enc = t_embd->ne[1];
  737. cross.v_embd.resize(cross.n_embd*cross.n_enc);
  738. memcpy(cross.v_embd.data(), embd, ggml_nbytes(t_embd));
  739. const auto & batch = balloc->get_batch();
  740. // remember the sequence ids used during the encoding - needed for cross attention later
  741. cross.seq_ids_enc.resize(n_tokens);
  742. for (uint32_t i = 0; i < n_tokens; i++) {
  743. cross.seq_ids_enc[i].clear();
  744. for (int s = 0; s < batch.n_seq_id[i]; s++) {
  745. const llama_seq_id seq_id = batch.seq_id[i][s];
  746. cross.seq_ids_enc[i].insert(seq_id);
  747. }
  748. }
  749. }
  750. return 0;
  751. }
  752. int llama_context::decode(const llama_batch & batch_inp) {
  753. GGML_ASSERT((!batch_inp.token && batch_inp.embd) || (batch_inp.token && !batch_inp.embd)); // NOLINT
  754. if (!memory) {
  755. LLAMA_LOG_DEBUG("%s: cannot decode batches with this context (calling encode() instead)\n", __func__);
  756. return encode(batch_inp);
  757. }
  758. if (batch_inp.n_tokens == 0) {
  759. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  760. return -1;
  761. }
  762. const auto & vocab = model.vocab;
  763. const auto & hparams = model.hparams;
  764. const int64_t n_vocab = vocab.n_tokens();
  765. const int64_t n_embd = hparams.n_embd;
  766. // when computing embeddings, all tokens are output
  767. const bool output_all = cparams.embeddings;
  768. if (!balloc->init(batch_inp, vocab, memory.get(), n_embd, cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max, output_all)) {
  769. LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
  770. return -1;
  771. }
  772. const uint32_t n_tokens_all = balloc->get_n_tokens();
  773. const uint32_t n_outputs_all = balloc->get_n_outputs();
  774. if (output_all) {
  775. // require that all tokens are output
  776. if (n_outputs_all != n_tokens_all) {
  777. LLAMA_LOG_ERROR("%s: pooled embedding requires that all tokens are output (n_outputs_all = %d, n_tokens_all = %d)\n",
  778. __func__, n_outputs_all, n_tokens_all);
  779. return -1;
  780. }
  781. }
  782. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  783. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  784. if (t_compute_start_us == 0) {
  785. t_compute_start_us = ggml_time_us();
  786. }
  787. n_queued_tokens += n_tokens_all;
  788. // TODO: this clear of the buffer can easily be forgotten - need something better
  789. embd_seq.clear();
  790. output_swaps.clear();
  791. bool did_optimize = false;
  792. // handle any pending defrags/shifts
  793. kv_self_update(false);
  794. llama_memory_context_ptr mctx;
  795. while (true) {
  796. mctx = memory->init_batch(*balloc, cparams.n_ubatch, output_all);
  797. if (!mctx) {
  798. return -2;
  799. }
  800. switch (mctx->get_status()) {
  801. case LLAMA_MEMORY_STATUS_SUCCESS:
  802. {
  803. } break;
  804. case LLAMA_MEMORY_STATUS_NO_UPDATE:
  805. {
  806. LLAMA_LOG_ERROR("%s: unexpected memory context status: %d\n", __func__, mctx->get_status());
  807. return -2;
  808. }
  809. case LLAMA_MEMORY_STATUS_FAILED_PREPARE:
  810. {
  811. if (!did_optimize) {
  812. did_optimize = true;
  813. if (kv_self_update(true)) {
  814. LLAMA_LOG_DEBUG("%s: retrying batch size %d after cache optimization\n", __func__, balloc->get_n_tokens());
  815. continue;
  816. }
  817. }
  818. LLAMA_LOG_WARN("%s: failed to find a memory slot for batch of size %d\n", __func__, balloc->get_n_tokens());
  819. return 1;
  820. }
  821. case LLAMA_MEMORY_STATUS_FAILED_COMPUTE:
  822. {
  823. LLAMA_LOG_ERROR("%s: compute failed while preparing batch of size %d\n", __func__, balloc->get_n_tokens());
  824. return -2;
  825. }
  826. }
  827. break;
  828. }
  829. // reserve output buffer
  830. if (output_reserve(n_outputs_all) < n_outputs_all) {
  831. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all);
  832. return -2;
  833. };
  834. int64_t n_outputs_prev = 0;
  835. do {
  836. const auto & ubatch = mctx->get_ubatch();
  837. // count the outputs in this ubatch
  838. {
  839. int32_t n_outputs_new = 0;
  840. if (n_outputs_all == n_tokens_all) {
  841. n_outputs_new = ubatch.n_tokens;
  842. } else {
  843. for (uint32_t i = 0; i < ubatch.n_tokens; i++) {
  844. n_outputs_new += (int32_t) (ubatch.output[i] != 0);
  845. }
  846. }
  847. // needs to happen before the graph is built
  848. n_outputs = n_outputs_new;
  849. }
  850. ggml_status status;
  851. const auto * res = process_ubatch(ubatch, LLM_GRAPH_TYPE_DECODER, mctx.get(), status);
  852. if (!res) {
  853. // the last ubatch failed or was aborted -> remove all positions of that ubatch from the KV cache
  854. llama_pos pos_min[LLAMA_MAX_SEQ];
  855. for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
  856. pos_min[s] = std::numeric_limits<llama_pos>::max();
  857. }
  858. for (uint32_t i = 0; i < ubatch.n_tokens; ++i) {
  859. const auto & seq_id = ubatch.seq_id[i][0];
  860. pos_min[seq_id] = std::min(pos_min[seq_id], ubatch.pos[i]);
  861. }
  862. for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
  863. if (pos_min[s] == std::numeric_limits<llama_pos>::max()) {
  864. continue;
  865. }
  866. LLAMA_LOG_WARN("%s: removing KV cache entries for seq_id = %d, pos = [%d, +inf)\n", __func__, s, pos_min[s]);
  867. memory->seq_rm(s, pos_min[s], -1);
  868. }
  869. switch (status) {
  870. case GGML_STATUS_ABORTED: return 2;
  871. case GGML_STATUS_ALLOC_FAILED: return -2;
  872. case GGML_STATUS_FAILED: return -3;
  873. case GGML_STATUS_SUCCESS: GGML_ABORT("should not happen");
  874. }
  875. }
  876. // plot the computation graph in dot format (for debugging purposes)
  877. //if (n_past%100 == 0) {
  878. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  879. //}
  880. auto * t_logits = res->get_logits();
  881. auto * t_embd = cparams.embeddings ? res->get_embd() : nullptr;
  882. if (t_embd && res->get_embd_pooled()) {
  883. t_embd = res->get_embd_pooled();
  884. }
  885. // extract logits
  886. if (t_logits && n_outputs > 0) {
  887. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits);
  888. GGML_ASSERT(backend_res != nullptr);
  889. GGML_ASSERT(logits != nullptr);
  890. float * logits_out = logits + n_outputs_prev*n_vocab;
  891. if (n_outputs) {
  892. GGML_ASSERT( n_outputs_prev + n_outputs <= n_outputs_all);
  893. GGML_ASSERT((n_outputs_prev + n_outputs)*n_vocab <= (int64_t) logits_size);
  894. ggml_backend_tensor_get_async(backend_res, t_logits, logits_out, 0, n_outputs*n_vocab*sizeof(float));
  895. }
  896. }
  897. // extract embeddings
  898. if (t_embd && n_outputs > 0) {
  899. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd);
  900. GGML_ASSERT(backend_embd != nullptr);
  901. switch (cparams.pooling_type) {
  902. case LLAMA_POOLING_TYPE_NONE:
  903. {
  904. // extract token embeddings
  905. GGML_ASSERT(embd != nullptr);
  906. float * embd_out = embd + n_outputs_prev*n_embd;
  907. if (n_outputs) {
  908. GGML_ASSERT( n_outputs_prev + n_outputs <= n_outputs_all);
  909. GGML_ASSERT((n_outputs_prev + n_outputs)*n_embd <= (int64_t) embd_size);
  910. ggml_backend_tensor_get_async(backend_embd, t_embd, embd_out, 0, n_outputs*n_embd*sizeof(float));
  911. }
  912. } break;
  913. case LLAMA_POOLING_TYPE_MEAN:
  914. case LLAMA_POOLING_TYPE_CLS:
  915. case LLAMA_POOLING_TYPE_LAST:
  916. {
  917. // extract sequence embeddings (cleared before processing each batch)
  918. auto & embd_seq_out = embd_seq;
  919. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  920. const llama_seq_id seq_id = ubatch.seq_id_unq[s];
  921. const int32_t seq_idx = ubatch.seq_idx[seq_id];
  922. embd_seq_out[seq_id].resize(n_embd);
  923. 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));
  924. }
  925. } break;
  926. case LLAMA_POOLING_TYPE_RANK:
  927. {
  928. // extract the rerank score - n_cls_out floats per sequence
  929. auto & embd_seq_out = embd_seq;
  930. const uint32_t n_cls_out = hparams.n_cls_out;
  931. for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
  932. const llama_seq_id seq_id = ubatch.seq_id_unq[s];
  933. const int32_t seq_idx = ubatch.seq_idx[seq_id];
  934. embd_seq_out[seq_id].resize(n_cls_out);
  935. 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));
  936. }
  937. } break;
  938. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  939. {
  940. GGML_ABORT("unknown pooling type");
  941. }
  942. }
  943. }
  944. n_outputs_prev += n_outputs;
  945. } while (mctx->next());
  946. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  947. n_outputs = n_outputs_all;
  948. // set output mappings
  949. if (n_outputs > 0) {
  950. bool sorted_output = true;
  951. auto & out_ids = balloc->get_out_ids();
  952. GGML_ASSERT(out_ids.size() == (size_t) n_outputs);
  953. for (int64_t i = 0; i < n_outputs; ++i) {
  954. int64_t out_id = out_ids[i];
  955. output_ids[out_id] = i;
  956. if (out_id != i) {
  957. sorted_output = false;
  958. }
  959. }
  960. // make the outputs have the same order they had in the user-provided batch
  961. // note: this is mostly relevant for recurrent models atm
  962. if (!sorted_output) {
  963. GGML_ASSERT((size_t) n_outputs == out_ids.size());
  964. // TODO: is there something more efficient which also minimizes swaps?
  965. // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
  966. for (uint32_t i = 0; i < n_outputs - 1; ++i) {
  967. uint32_t j_min = i;
  968. for (uint32_t j = i + 1; j < n_outputs; ++j) {
  969. if (out_ids[j] < out_ids[j_min]) {
  970. j_min = j;
  971. }
  972. }
  973. if (j_min == i) {
  974. continue;
  975. }
  976. std::swap(out_ids[i], out_ids[j_min]);
  977. // remember the swaps and apply them lazily upon logits/embeddings access
  978. output_swaps.push_back({ i, j_min });
  979. }
  980. std::fill(output_ids.begin(), output_ids.end(), -1);
  981. for (uint32_t i = 0; i < n_outputs; ++i) {
  982. output_ids[out_ids[i]] = i;
  983. }
  984. }
  985. }
  986. // wait for the computation to finish (automatically done when obtaining the model output)
  987. //synchronize();
  988. if (!supports_set_rows) {
  989. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  990. // overlap with device computation.
  991. ggml_backend_sched_reset(sched.get());
  992. }
  993. return 0;
  994. }
  995. //
  996. // output
  997. //
  998. uint32_t llama_context::output_reserve(int32_t n_outputs) {
  999. const auto & hparams = model.hparams;
  1000. const auto & vocab = model.vocab;
  1001. const int64_t n_outputs_max = std::max<int64_t>(n_outputs, n_seq_max());
  1002. const auto n_batch = cparams.n_batch;
  1003. const auto n_vocab = vocab.n_tokens();
  1004. const auto n_embd = hparams.n_embd;
  1005. bool has_logits = true;
  1006. bool has_embd = cparams.embeddings;
  1007. // TODO: hacky enc-dec support
  1008. if (model.arch == LLM_ARCH_T5) {
  1009. has_logits = true;
  1010. has_embd = true;
  1011. }
  1012. logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  1013. embd_size = has_embd ? n_embd*n_outputs_max : 0;
  1014. if (output_ids.empty()) {
  1015. // init, never resized afterwards
  1016. output_ids.resize(n_batch);
  1017. }
  1018. const size_t prev_size = buf_output ? ggml_backend_buffer_get_size(buf_output.get()) : 0;
  1019. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  1020. // alloc only when more than the current capacity is required
  1021. // TODO: also consider shrinking the buffer
  1022. if (!buf_output || prev_size < new_size) {
  1023. if (buf_output) {
  1024. #ifndef NDEBUG
  1025. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  1026. LLAMA_LOG_INFO("%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);
  1027. #endif
  1028. buf_output = nullptr;
  1029. logits = nullptr;
  1030. embd = nullptr;
  1031. }
  1032. auto * buft = ggml_backend_cpu_buffer_type();
  1033. // try to use the host buffer of the device where the output tensor is allocated for faster transfer to system memory
  1034. auto * output_dev = model.dev_output();
  1035. auto * output_dev_host_buft = output_dev ? ggml_backend_dev_host_buffer_type(output_dev) : nullptr;
  1036. if (output_dev_host_buft) {
  1037. buft = output_dev_host_buft;
  1038. }
  1039. buf_output.reset(ggml_backend_buft_alloc_buffer(buft, new_size));
  1040. if (buf_output == nullptr) {
  1041. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  1042. return 0;
  1043. }
  1044. }
  1045. float * output_base = (float *) ggml_backend_buffer_get_base(buf_output.get());
  1046. logits = has_logits ? output_base : nullptr;
  1047. embd = has_embd ? output_base + logits_size : nullptr;
  1048. // set all ids as invalid (negative)
  1049. std::fill(output_ids.begin(), output_ids.end(), -1);
  1050. this->n_outputs = 0;
  1051. return n_outputs_max;
  1052. }
  1053. void llama_context::output_reorder() {
  1054. const uint64_t n_vocab = model.vocab.n_tokens();
  1055. const uint64_t n_embd = model.hparams.n_embd;
  1056. for (size_t s = 0; s < output_swaps.size(); ++s) {
  1057. const uint64_t i0 = output_swaps[s].i0;
  1058. const uint64_t i1 = output_swaps[s].i1;
  1059. if (logits_size > 0) {
  1060. for (uint64_t k = 0; k < n_vocab; k++) {
  1061. std::swap(logits[i0*n_vocab + k], logits[i1*n_vocab + k]);
  1062. }
  1063. }
  1064. if (embd_size > 0) {
  1065. for (uint64_t k = 0; k < n_embd; k++) {
  1066. std::swap(embd[i0*n_embd + k], embd[i1*n_embd + k]);
  1067. }
  1068. }
  1069. }
  1070. output_swaps.clear();
  1071. }
  1072. //
  1073. // graph
  1074. //
  1075. uint32_t llama_context::graph_max_nodes() const {
  1076. return std::max<uint32_t>(1024u, 8u*model.n_tensors());
  1077. }
  1078. llm_graph_result * llama_context::get_gf_res_reserve() const {
  1079. return static_cast<llm_graph_result *>(gf_res_reserve.get());
  1080. }
  1081. ggml_cgraph * llama_context::graph_reserve(uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx) {
  1082. 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);
  1083. if (n_tokens % n_seqs != 0) {
  1084. n_tokens = ((n_tokens + (n_seqs - 1)) / n_seqs) * n_seqs; // round to next multiple of n_seqs
  1085. n_outputs = std::min(n_outputs, n_tokens);
  1086. 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);
  1087. }
  1088. ggml_backend_sched_reset(sched.get());
  1089. // when the scheduler is reset, we cannnot reuse the old graph, so we reset the previous graph result to prevent that
  1090. gf_res_prev->reset();
  1091. // store the n_outputs as it is, and restore it afterwards
  1092. // TODO: not sure if needed, might simplify in the future by removing this
  1093. const auto save_n_outputs = this->n_outputs;
  1094. this->n_outputs = n_outputs;
  1095. llama_batch_allocr balloc(model.hparams.n_pos_per_embd());
  1096. llama_ubatch ubatch = balloc.ubatch_reserve(n_tokens/n_seqs, n_seqs);
  1097. auto * res = gf_res_reserve.get();
  1098. const auto gparams = graph_params(res, ubatch, mctx, LLM_GRAPH_TYPE_DEFAULT);
  1099. res->reset();
  1100. auto * gf = model.build_graph(gparams);
  1101. this->n_outputs = save_n_outputs;
  1102. // initialize scheduler with the specified graph
  1103. if (!ggml_backend_sched_reserve(sched.get(), gf)) {
  1104. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  1105. return nullptr;
  1106. }
  1107. return gf;
  1108. }
  1109. llm_graph_params llama_context::graph_params(
  1110. llm_graph_result * res,
  1111. const llama_ubatch & ubatch,
  1112. const llama_memory_context_i * mctx,
  1113. llm_graph_type gtype) const {
  1114. return {
  1115. /*.arch =*/ model.arch,
  1116. /*.hparams =*/ model.hparams,
  1117. /*.cparams =*/ cparams,
  1118. /*.ubatch =*/ ubatch,
  1119. /*.gtype =*/ gtype,
  1120. /*.sched =*/ sched.get(),
  1121. /*.backend_cpu =*/ backend_cpu,
  1122. /*.cvec =*/ &cvec,
  1123. /*.loras =*/ &loras,
  1124. /*.mctx =*/ mctx,
  1125. /*.cross =*/ &cross,
  1126. /*.n_outputs =*/ n_outputs,
  1127. /*.cb =*/ graph_get_cb(),
  1128. /*.res =*/ res,
  1129. };
  1130. }
  1131. ggml_status llama_context::graph_compute(
  1132. ggml_cgraph * gf,
  1133. bool batched) {
  1134. int n_threads = batched ? cparams.n_threads_batch : cparams.n_threads;
  1135. ggml_threadpool_t tp = batched ? threadpool_batch : threadpool;
  1136. if (backend_cpu != nullptr) {
  1137. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend_cpu));
  1138. auto * set_threadpool_fn = (decltype(ggml_backend_cpu_set_threadpool) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_set_threadpool");
  1139. set_threadpool_fn(backend_cpu, tp);
  1140. }
  1141. // set the number of threads for all the backends
  1142. for (const auto & set_n_threads_fn : set_n_threads_fns) {
  1143. set_n_threads_fn.second(set_n_threads_fn.first, n_threads);
  1144. }
  1145. auto status = ggml_backend_sched_graph_compute_async(sched.get(), gf);
  1146. if (status != GGML_STATUS_SUCCESS) {
  1147. LLAMA_LOG_ERROR("%s: ggml_backend_sched_graph_compute_async failed with error %d\n", __func__, status);
  1148. }
  1149. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(sched));
  1150. return status;
  1151. }
  1152. llm_graph_cb llama_context::graph_get_cb() const {
  1153. return [&](const llama_ubatch & ubatch, ggml_tensor * cur, const char * name, int il) {
  1154. if (il >= 0) {
  1155. ggml_format_name(cur, "%s-%d", name, il);
  1156. } else {
  1157. ggml_set_name(cur, name);
  1158. }
  1159. if (!cparams.offload_kqv) {
  1160. if (strcmp(name, "kqv_merged_cont") == 0) {
  1161. // all nodes between the KV store and the attention output are run on the CPU
  1162. ggml_backend_sched_set_tensor_backend(sched.get(), cur, backend_cpu);
  1163. }
  1164. }
  1165. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  1166. // FIXME: fix in ggml_backend_sched
  1167. const bool full_offload = model.params.n_gpu_layers > (int) model.hparams.n_layer;
  1168. if (ubatch.n_tokens < 32 || full_offload) {
  1169. if (il != -1 && strcmp(name, "norm") == 0) {
  1170. const auto & dev_layer = model.dev_layer(il);
  1171. for (const auto & backend : backends) {
  1172. if (ggml_backend_get_device(backend.get()) == dev_layer) {
  1173. if (ggml_backend_supports_op(backend.get(), cur)) {
  1174. ggml_backend_sched_set_tensor_backend(sched.get(), cur, backend.get());
  1175. }
  1176. }
  1177. }
  1178. }
  1179. }
  1180. };
  1181. }
  1182. //
  1183. // state save/load
  1184. //
  1185. class llama_io_write_dummy : public llama_io_write_i {
  1186. public:
  1187. llama_io_write_dummy() = default;
  1188. void write(const void * /* src */, size_t size) override {
  1189. size_written += size;
  1190. }
  1191. void write_tensor(const ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
  1192. size_written += size;
  1193. }
  1194. size_t n_bytes() override {
  1195. return size_written;
  1196. }
  1197. private:
  1198. size_t size_written = 0;
  1199. };
  1200. class llama_io_write_buffer : public llama_io_write_i {
  1201. public:
  1202. llama_io_write_buffer(
  1203. uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  1204. void write(const void * src, size_t size) override {
  1205. if (size > buf_size) {
  1206. throw std::runtime_error("unexpectedly reached end of buffer");
  1207. }
  1208. memcpy(ptr, src, size);
  1209. ptr += size;
  1210. size_written += size;
  1211. buf_size -= size;
  1212. }
  1213. void write_tensor(const ggml_tensor * tensor, size_t offset, size_t size) override {
  1214. if (size > buf_size) {
  1215. throw std::runtime_error("unexpectedly reached end of buffer");
  1216. }
  1217. ggml_backend_tensor_get(tensor, ptr, offset, size);
  1218. ptr += size;
  1219. size_written += size;
  1220. buf_size -= size;
  1221. }
  1222. size_t n_bytes() override {
  1223. return size_written;
  1224. }
  1225. private:
  1226. uint8_t * ptr;
  1227. size_t buf_size = 0;
  1228. size_t size_written = 0;
  1229. };
  1230. class llama_io_read_buffer : public llama_io_read_i {
  1231. public:
  1232. llama_io_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  1233. const uint8_t * read(size_t size) override {
  1234. const uint8_t * base_ptr = ptr;
  1235. if (size > buf_size) {
  1236. throw std::runtime_error("unexpectedly reached end of buffer");
  1237. }
  1238. ptr += size;
  1239. size_read += size;
  1240. buf_size -= size;
  1241. return base_ptr;
  1242. }
  1243. void read_to(void * dst, size_t size) override {
  1244. memcpy(dst, read(size), size);
  1245. }
  1246. size_t n_bytes() override {
  1247. return size_read;
  1248. }
  1249. private:
  1250. const uint8_t * ptr;
  1251. size_t buf_size = 0;
  1252. size_t size_read = 0;
  1253. };
  1254. class llama_io_write_file : public llama_io_write_i {
  1255. public:
  1256. llama_io_write_file(llama_file * f) : file(f) {}
  1257. void write(const void * src, size_t size) override {
  1258. file->write_raw(src, size);
  1259. size_written += size;
  1260. }
  1261. void write_tensor(const ggml_tensor * tensor, size_t offset, size_t size) override {
  1262. temp_buffer.resize(size);
  1263. ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
  1264. write(temp_buffer.data(), temp_buffer.size());
  1265. }
  1266. size_t n_bytes() override {
  1267. return size_written;
  1268. }
  1269. private:
  1270. llama_file * file;
  1271. size_t size_written = 0;
  1272. std::vector<uint8_t> temp_buffer;
  1273. };
  1274. class llama_io_read_file : public llama_io_read_i {
  1275. public:
  1276. llama_io_read_file(llama_file * f) : file(f) {}
  1277. void read_to(void * dst, size_t size) override {
  1278. file->read_raw(dst, size);
  1279. size_read += size;
  1280. }
  1281. const uint8_t * read(size_t size) override {
  1282. temp_buffer.resize(size);
  1283. read_to(temp_buffer.data(), size);
  1284. return temp_buffer.data();
  1285. }
  1286. size_t n_bytes() override {
  1287. return size_read;
  1288. }
  1289. private:
  1290. llama_file * file;
  1291. size_t size_read = 0;
  1292. std::vector<uint8_t> temp_buffer;
  1293. };
  1294. size_t llama_context::state_get_size() {
  1295. llama_io_write_dummy io;
  1296. try {
  1297. return state_write_data(io);
  1298. } catch (const std::exception & err) {
  1299. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  1300. return 0;
  1301. }
  1302. }
  1303. size_t llama_context::state_get_data(uint8_t * dst, size_t size) {
  1304. llama_io_write_buffer io(dst, size);
  1305. try {
  1306. return state_write_data(io);
  1307. } catch (const std::exception & err) {
  1308. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  1309. return 0;
  1310. }
  1311. }
  1312. size_t llama_context::state_set_data(const uint8_t * src, size_t size) {
  1313. llama_io_read_buffer io(src, size);
  1314. try {
  1315. return state_read_data(io);
  1316. } catch (const std::exception & err) {
  1317. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  1318. return 0;
  1319. }
  1320. }
  1321. size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_flags flags) {
  1322. llama_io_write_dummy io;
  1323. try {
  1324. return state_seq_write_data(io, seq_id, flags);
  1325. } catch (const std::exception & err) {
  1326. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  1327. return 0;
  1328. }
  1329. }
  1330. size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, size_t size, llama_state_seq_flags flags) {
  1331. llama_io_write_buffer io(dst, size);
  1332. try {
  1333. return state_seq_write_data(io, seq_id, flags);
  1334. } catch (const std::exception & err) {
  1335. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  1336. return 0;
  1337. }
  1338. }
  1339. 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) {
  1340. llama_io_read_buffer io(src, size);
  1341. try {
  1342. return state_seq_read_data(io, seq_id, flags);
  1343. } catch (const std::exception & err) {
  1344. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  1345. return 0;
  1346. }
  1347. }
  1348. bool llama_context::state_load_file(const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  1349. llama_file file(filepath, "rb");
  1350. // sanity checks
  1351. {
  1352. const uint32_t magic = file.read_u32();
  1353. const uint32_t version = file.read_u32();
  1354. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  1355. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  1356. return false;
  1357. }
  1358. }
  1359. // load the prompt
  1360. {
  1361. const uint32_t n_token_count = file.read_u32();
  1362. if (n_token_count > n_token_capacity) {
  1363. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  1364. return false;
  1365. }
  1366. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  1367. *n_token_count_out = n_token_count;
  1368. }
  1369. // restore the context state
  1370. {
  1371. const size_t n_state_size_cur = file.size() - file.tell();
  1372. llama_io_read_file io( &file);
  1373. const size_t n_read = state_read_data(io);
  1374. if (n_read != n_state_size_cur) {
  1375. 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);
  1376. return false;
  1377. }
  1378. }
  1379. return true;
  1380. }
  1381. bool llama_context::state_save_file(const char * filepath, const llama_token * tokens, size_t n_token_count) {
  1382. llama_file file(filepath, "wb");
  1383. file.write_u32(LLAMA_SESSION_MAGIC);
  1384. file.write_u32(LLAMA_SESSION_VERSION);
  1385. // save the prompt
  1386. file.write_u32((uint32_t) n_token_count);
  1387. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  1388. // save the context state using stream saving
  1389. llama_io_write_file io(&file);
  1390. state_write_data(io);
  1391. return true;
  1392. }
  1393. 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) {
  1394. llama_file file(filepath, "rb");
  1395. // version checks
  1396. {
  1397. const uint32_t magic = file.read_u32();
  1398. const uint32_t version = file.read_u32();
  1399. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  1400. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  1401. return 0;
  1402. }
  1403. }
  1404. // load the prompt
  1405. {
  1406. const uint32_t n_token_count = file.read_u32();
  1407. if (n_token_count > n_token_capacity) {
  1408. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  1409. return 0;
  1410. }
  1411. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  1412. *n_token_count_out = n_token_count;
  1413. }
  1414. // restore the context state
  1415. {
  1416. const size_t state_size = file.size() - file.tell();
  1417. llama_io_read_file io(&file);
  1418. const size_t nread = state_seq_read_data(io, seq_id, 0);
  1419. if (!nread) {
  1420. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  1421. return 0;
  1422. }
  1423. GGML_ASSERT(nread <= state_size);
  1424. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  1425. }
  1426. return file.tell();
  1427. }
  1428. 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) {
  1429. llama_file file(filepath, "wb");
  1430. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  1431. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  1432. // save the prompt
  1433. file.write_u32((uint32_t) n_token_count);
  1434. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  1435. // save the context state using stream saving
  1436. llama_io_write_file io(&file);
  1437. state_seq_write_data(io, seq_id, 0);
  1438. const size_t res = file.tell();
  1439. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + io.n_bytes());
  1440. return res;
  1441. }
  1442. size_t llama_context::state_write_data(llama_io_write_i & io) {
  1443. LLAMA_LOG_DEBUG("%s: writing state\n", __func__);
  1444. // write model info
  1445. {
  1446. LLAMA_LOG_DEBUG("%s: - writing model info\n", __func__);
  1447. const std::string arch_str = llm_arch_name(model.arch);
  1448. io.write_string(arch_str);
  1449. // TODO: add more model-specific info which should prevent loading the session file if not identical
  1450. }
  1451. // write output ids
  1452. {
  1453. LLAMA_LOG_DEBUG("%s: - writing output ids\n", __func__);
  1454. const auto n_outputs = this->n_outputs;
  1455. const auto & output_ids = this->output_ids;
  1456. std::vector<int32_t> w_output_pos;
  1457. w_output_pos.resize(n_outputs);
  1458. // build a more compact representation of the output ids
  1459. for (size_t i = 0; i < n_batch(); ++i) {
  1460. // map an output id to a position in the batch
  1461. int64_t pos = output_ids[i];
  1462. if (pos >= 0) {
  1463. GGML_ASSERT(pos < n_outputs);
  1464. w_output_pos[pos] = i;
  1465. }
  1466. }
  1467. io.write(&n_outputs, sizeof(n_outputs));
  1468. if (n_outputs) {
  1469. io.write(w_output_pos.data(), n_outputs * sizeof(int32_t));
  1470. }
  1471. }
  1472. // write logits
  1473. {
  1474. LLAMA_LOG_DEBUG("%s: - writing logits\n", __func__);
  1475. const uint64_t logits_size = std::min((uint64_t) this->logits_size, (uint64_t) n_outputs * model.vocab.n_tokens());
  1476. io.write(&logits_size, sizeof(logits_size));
  1477. if (logits_size) {
  1478. io.write(logits, logits_size * sizeof(float));
  1479. }
  1480. }
  1481. // write embeddings
  1482. {
  1483. LLAMA_LOG_DEBUG("%s: - writing embeddings\n", __func__);
  1484. const uint64_t embd_size = std::min((uint64_t) this->embd_size, (uint64_t) n_outputs * model.hparams.n_embd);
  1485. io.write(&embd_size, sizeof(embd_size));
  1486. if (embd_size) {
  1487. io.write(embd, embd_size * sizeof(float));
  1488. }
  1489. }
  1490. if (memory != nullptr) {
  1491. LLAMA_LOG_DEBUG("%s: - writing KV self\n", __func__);
  1492. memory->state_write(io);
  1493. }
  1494. return io.n_bytes();
  1495. }
  1496. size_t llama_context::state_read_data(llama_io_read_i & io) {
  1497. LLAMA_LOG_DEBUG("%s: reading state\n", __func__);
  1498. // read model info
  1499. {
  1500. LLAMA_LOG_DEBUG("%s: - reading model info\n", __func__);
  1501. const std::string cur_arch_str = llm_arch_name(model.arch);
  1502. std::string arch_str;
  1503. io.read_string(arch_str);
  1504. if (cur_arch_str != arch_str) {
  1505. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  1506. }
  1507. // TODO: add more info which needs to be identical but which is not verified otherwise
  1508. }
  1509. // read output ids
  1510. {
  1511. LLAMA_LOG_DEBUG("%s: - reading output ids\n", __func__);
  1512. auto n_outputs = this->n_outputs;
  1513. io.read_to(&n_outputs, sizeof(n_outputs));
  1514. if (n_outputs > output_reserve(n_outputs)) {
  1515. throw std::runtime_error("could not reserve outputs");
  1516. }
  1517. std::vector<int32_t> output_pos;
  1518. if (n_outputs) {
  1519. output_pos.resize(n_outputs);
  1520. io.read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  1521. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  1522. int32_t id = output_pos[i];
  1523. if ((uint32_t) id >= n_batch()) {
  1524. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, n_batch()));
  1525. }
  1526. this->output_ids[id] = i;
  1527. }
  1528. this->n_outputs = n_outputs;
  1529. }
  1530. }
  1531. // read logits
  1532. {
  1533. LLAMA_LOG_DEBUG("%s: - reading logits\n", __func__);
  1534. uint64_t logits_size;
  1535. io.read_to(&logits_size, sizeof(logits_size));
  1536. if (this->logits_size < logits_size) {
  1537. throw std::runtime_error("logits buffer too small");
  1538. }
  1539. if (logits_size) {
  1540. io.read_to(this->logits, logits_size * sizeof(float));
  1541. }
  1542. }
  1543. // read embeddings
  1544. {
  1545. LLAMA_LOG_DEBUG("%s: - reading embeddings\n", __func__);
  1546. uint64_t embd_size;
  1547. io.read_to(&embd_size, sizeof(embd_size));
  1548. if (this->embd_size < embd_size) {
  1549. throw std::runtime_error("embeddings buffer too small");
  1550. }
  1551. if (embd_size) {
  1552. io.read_to(this->embd, embd_size * sizeof(float));
  1553. }
  1554. }
  1555. if (memory) {
  1556. LLAMA_LOG_DEBUG("%s: - reading KV self\n", __func__);
  1557. memory->state_read(io);
  1558. }
  1559. return io.n_bytes();
  1560. }
  1561. size_t llama_context::state_seq_write_data(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
  1562. GGML_UNUSED(seq_id);
  1563. if (memory) {
  1564. memory->state_write(io, seq_id, flags);
  1565. }
  1566. return io.n_bytes();
  1567. }
  1568. size_t llama_context::state_seq_read_data(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
  1569. GGML_UNUSED(seq_id);
  1570. if (memory) {
  1571. memory->state_read(io, seq_id, flags);
  1572. }
  1573. return io.n_bytes();
  1574. }
  1575. //
  1576. // perf
  1577. //
  1578. llama_perf_context_data llama_context::perf_get_data() const {
  1579. llama_perf_context_data data = {};
  1580. data.t_start_ms = 1e-3 * t_start_us;
  1581. data.t_load_ms = 1e-3 * t_load_us;
  1582. data.t_p_eval_ms = 1e-3 * t_p_eval_us;
  1583. data.t_eval_ms = 1e-3 * t_eval_us;
  1584. data.n_p_eval = std::max(1, n_p_eval);
  1585. data.n_eval = std::max(1, n_eval);
  1586. data.n_reused = std::max(0, n_reused);
  1587. return data;
  1588. }
  1589. void llama_context::perf_reset() {
  1590. t_start_us = ggml_time_us();
  1591. t_eval_us = n_eval = 0;
  1592. t_p_eval_us = n_p_eval = 0;
  1593. n_reused = 0;
  1594. }
  1595. //
  1596. // training
  1597. //
  1598. static void llama_set_param(struct ggml_tensor * tensor, llama_opt_param_filter param_filter, void * userdata) {
  1599. if (!tensor || tensor->type != GGML_TYPE_F32) {
  1600. return;
  1601. }
  1602. if (!param_filter(tensor, userdata)) {
  1603. return;
  1604. }
  1605. if (strcmp(tensor->name, "token_embd.weight") == 0) {
  1606. return; // FIXME
  1607. }
  1608. if (strcmp(tensor->name, "rope_freqs.weight") == 0) {
  1609. return; // FIXME
  1610. }
  1611. ggml_set_param(tensor);
  1612. }
  1613. void llama_context::opt_init(struct llama_model * model, struct llama_opt_params lopt_params) {
  1614. GGML_ASSERT(!opt_ctx);
  1615. model->hparams.n_ctx_train = lopt_params.n_ctx_train > 0 ? lopt_params.n_ctx_train : n_ctx();
  1616. const uint32_t n_batch = std::min(this->n_batch(), model->hparams.n_ctx_train);
  1617. const uint32_t n_ubatch = std::min(this->n_ubatch(), n_batch);
  1618. GGML_ASSERT(model->hparams.n_ctx_train % n_batch == 0);
  1619. GGML_ASSERT(n_batch % n_ubatch == 0);
  1620. ggml_opt_params opt_params = ggml_opt_default_params(sched.get(), GGML_OPT_LOSS_TYPE_CROSS_ENTROPY);
  1621. opt_params.opt_period = n_batch / n_ubatch;
  1622. opt_params.get_opt_pars = lopt_params.get_opt_pars;
  1623. opt_params.get_opt_pars_ud = lopt_params.get_opt_pars_ud;
  1624. opt_params.optimizer = lopt_params.optimizer_type;
  1625. opt_ctx = ggml_opt_init(opt_params);
  1626. llama_opt_param_filter param_filter = lopt_params.param_filter;
  1627. void * param_filter_ud = lopt_params.param_filter_ud;
  1628. //llama_set_param(model->tok_embd, param_filter, param_filter_ud); // FIXME
  1629. llama_set_param(model->type_embd, param_filter, param_filter_ud);
  1630. llama_set_param(model->pos_embd, param_filter, param_filter_ud);
  1631. llama_set_param(model->tok_norm, param_filter, param_filter_ud);
  1632. llama_set_param(model->tok_norm_b, param_filter, param_filter_ud);
  1633. llama_set_param(model->output_norm, param_filter, param_filter_ud);
  1634. llama_set_param(model->output_norm_b, param_filter, param_filter_ud);
  1635. llama_set_param(model->output, param_filter, param_filter_ud);
  1636. llama_set_param(model->output_b, param_filter, param_filter_ud);
  1637. llama_set_param(model->output_norm_enc, param_filter, param_filter_ud);
  1638. llama_set_param(model->cls, param_filter, param_filter_ud);
  1639. llama_set_param(model->cls_b, param_filter, param_filter_ud);
  1640. llama_set_param(model->cls_out, param_filter, param_filter_ud);
  1641. llama_set_param(model->cls_out_b, param_filter, param_filter_ud);
  1642. for (struct llama_layer & layer : model->layers) {
  1643. for (size_t i = 0; i < sizeof(layer)/sizeof(struct ggml_tensor *); ++i) {
  1644. llama_set_param(reinterpret_cast<struct ggml_tensor **>(&layer)[i], param_filter, param_filter_ud);
  1645. }
  1646. }
  1647. }
  1648. void llama_context::opt_epoch_iter(
  1649. ggml_opt_dataset_t dataset,
  1650. ggml_opt_result_t result,
  1651. const std::vector<llama_token> & tokens,
  1652. const std::vector<llama_token> & labels_sparse,
  1653. llama_batch & batch,
  1654. ggml_opt_epoch_callback callback,
  1655. bool train,
  1656. int64_t idata_in_loop,
  1657. int64_t ndata_in_loop,
  1658. int64_t t_loop_start) {
  1659. GGML_ASSERT(opt_ctx);
  1660. const uint32_t n_ctx = llama_model_n_ctx_train(&model);
  1661. const uint32_t n_batch = std::min(this->n_batch(), n_ctx);
  1662. const uint32_t n_ubatch = std::min(this->n_ubatch(), n_batch);
  1663. memory->clear(true);
  1664. for (uint32_t pos_ctx = 0; pos_ctx < n_ctx; pos_ctx += n_batch) {
  1665. batch.n_tokens = n_batch;
  1666. for (uint32_t pos_batch = 0; pos_batch < n_batch; ++pos_batch) {
  1667. batch.token [pos_batch] = tokens[pos_ctx + pos_batch];
  1668. batch.pos [pos_batch] = pos_ctx + pos_batch;
  1669. batch.n_seq_id[pos_batch] = 1;
  1670. batch.seq_id [pos_batch][0] = 0;
  1671. batch.logits [pos_batch] = true;
  1672. }
  1673. if (!balloc->init(batch, model.vocab, nullptr, model.hparams.n_embd, cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max, true)) {
  1674. LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
  1675. return;
  1676. }
  1677. const uint32_t n_tokens_all = balloc->get_n_tokens();
  1678. n_queued_tokens += n_tokens_all;
  1679. embd_seq.clear();
  1680. uint32_t n_outputs_all = n_tokens_all;
  1681. auto mctx = memory->init_batch(*balloc, cparams.n_ubatch, true);
  1682. if (!mctx || mctx->get_status() != LLAMA_MEMORY_STATUS_SUCCESS) {
  1683. LLAMA_LOG_ERROR("%s: could not initialize batch\n", __func__);
  1684. break;
  1685. }
  1686. // reserve output buffer
  1687. if (output_reserve(n_outputs_all) < n_outputs_all) {
  1688. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all);
  1689. GGML_ABORT("TODO: handle this error");
  1690. };
  1691. uint32_t pos_batch = 0;
  1692. do {
  1693. const auto & ubatch = mctx->get_ubatch();
  1694. n_outputs = ubatch.n_tokens;
  1695. if (!mctx->apply()) {
  1696. LLAMA_LOG_ERROR("%s: failed to update the memory context\n", __func__);
  1697. break;
  1698. }
  1699. auto * res = gf_res_prev.get();
  1700. const auto gparams = graph_params(res, ubatch, mctx.get(), LLM_GRAPH_TYPE_DEFAULT);
  1701. res->reset();
  1702. auto * gf = model.build_graph(gparams);
  1703. struct ggml_context * ctx_compute_opt;
  1704. {
  1705. const size_t size_gf = ggml_graph_size(gf);
  1706. const size_t size_meta = 4*size_gf*ggml_tensor_overhead() + 2*ggml_graph_overhead_custom(size_gf, /*grads = */ true);
  1707. struct ggml_init_params params = {
  1708. /*.mem_size =*/ size_meta,
  1709. /*.mem_buffer =*/ nullptr,
  1710. /*.no_alloc =*/ true,
  1711. };
  1712. ctx_compute_opt = ggml_init(params);
  1713. }
  1714. ggml_opt_prepare_alloc(opt_ctx, ctx_compute_opt, gf, res->get_tokens(), res->get_logits());
  1715. ggml_opt_alloc(opt_ctx, train);
  1716. res->set_inputs(&ubatch);
  1717. {
  1718. struct ggml_tensor * labels = ggml_opt_labels(opt_ctx);
  1719. GGML_ASSERT(labels->ne[1] == n_ubatch);
  1720. ggml_set_zero(labels);
  1721. const float onef = 1.0f;
  1722. for (uint32_t pos_ubatch = 0; pos_ubatch < n_ubatch; ++pos_ubatch) {
  1723. const uint32_t ilabel = pos_ctx + pos_batch + pos_ubatch;
  1724. GGML_ASSERT(labels_sparse[ilabel] < labels->ne[0]);
  1725. ggml_backend_tensor_set(labels, &onef, (pos_ubatch*labels->ne[0] + labels_sparse[ilabel])*sizeof(float), sizeof(float));
  1726. }
  1727. }
  1728. ggml_opt_eval(opt_ctx, result);
  1729. if (callback) {
  1730. callback(train, opt_ctx, dataset, result, idata_in_loop + (pos_ctx + pos_batch)/n_ubatch + 1, ndata_in_loop, t_loop_start);
  1731. }
  1732. ggml_free(ctx_compute_opt);
  1733. pos_batch += ubatch.n_tokens;
  1734. } while (mctx->next());
  1735. }
  1736. }
  1737. void llama_context::opt_epoch(
  1738. ggml_opt_dataset_t dataset,
  1739. ggml_opt_result_t result_train,
  1740. ggml_opt_result_t result_eval,
  1741. int64_t idata_split,
  1742. ggml_opt_epoch_callback callback_train,
  1743. ggml_opt_epoch_callback callback_eval) {
  1744. const uint32_t n_ctx = this->n_ctx();
  1745. const uint32_t n_batch = std::min(cparams.n_batch, n_ctx);
  1746. const uint32_t n_ubatch = std::min(cparams.n_ubatch, n_batch);
  1747. const int64_t ndata = ggml_opt_dataset_ndata(dataset);
  1748. GGML_ASSERT(idata_split >= 0);
  1749. GGML_ASSERT(idata_split <= ndata);
  1750. const uint32_t ubatch_per_ctx = n_ctx / n_ubatch;
  1751. struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
  1752. std::vector<llama_token> tokens(n_ctx);
  1753. std::vector<llama_token> labels_sparse(n_ctx);
  1754. int64_t idata = 0;
  1755. int64_t t_loop_start = ggml_time_us();
  1756. int64_t ndata_in_loop = idata_split*ubatch_per_ctx;
  1757. for (; idata < idata_split; ++idata) {
  1758. constexpr bool train = true;
  1759. const int64_t idata_in_loop = idata*ubatch_per_ctx;
  1760. ggml_opt_dataset_get_batch_host(dataset, tokens.data(), n_ctx*sizeof(llama_token), labels_sparse.data(), idata);
  1761. opt_epoch_iter(dataset, result_train, tokens, labels_sparse, batch,
  1762. callback_train, train, idata_in_loop, ndata_in_loop, t_loop_start);
  1763. }
  1764. t_loop_start = ggml_time_us();
  1765. ndata_in_loop = (ndata - idata_split)*ubatch_per_ctx;
  1766. for (; idata < ndata; ++idata) {
  1767. constexpr bool train = false;
  1768. const int64_t idata_in_loop = (idata - idata_split)*ubatch_per_ctx;
  1769. ggml_opt_dataset_get_batch_host(dataset, tokens.data(), n_ctx*sizeof(llama_token), labels_sparse.data(), idata);
  1770. opt_epoch_iter(dataset, result_eval, tokens, labels_sparse, batch,
  1771. callback_eval, train, idata_in_loop, ndata_in_loop, t_loop_start);
  1772. }
  1773. llama_batch_free(batch);
  1774. }
  1775. //
  1776. // interface implementation
  1777. //
  1778. llama_context_params llama_context_default_params() {
  1779. llama_context_params result = {
  1780. /*.n_ctx =*/ 512,
  1781. /*.n_batch =*/ 2048,
  1782. /*.n_ubatch =*/ 512,
  1783. /*.n_seq_max =*/ 1,
  1784. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  1785. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  1786. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  1787. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  1788. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  1789. /*.rope_freq_base =*/ 0.0f,
  1790. /*.rope_freq_scale =*/ 0.0f,
  1791. /*.yarn_ext_factor =*/ -1.0f,
  1792. /*.yarn_attn_factor =*/ 1.0f,
  1793. /*.yarn_beta_fast =*/ 32.0f,
  1794. /*.yarn_beta_slow =*/ 1.0f,
  1795. /*.yarn_orig_ctx =*/ 0,
  1796. /*.defrag_thold =*/ -1.0f,
  1797. /*.cb_eval =*/ nullptr,
  1798. /*.cb_eval_user_data =*/ nullptr,
  1799. /*.type_k =*/ GGML_TYPE_F16,
  1800. /*.type_v =*/ GGML_TYPE_F16,
  1801. /*.abort_callback =*/ nullptr,
  1802. /*.abort_callback_data =*/ nullptr,
  1803. /*.embeddings =*/ false,
  1804. /*.offload_kqv =*/ true,
  1805. /*.flash_attn =*/ false,
  1806. /*.no_perf =*/ true,
  1807. /*.op_offload =*/ true,
  1808. /*.swa_full =*/ true,
  1809. /*.kv_unified =*/ false,
  1810. };
  1811. return result;
  1812. }
  1813. llama_context * llama_init_from_model(
  1814. llama_model * model,
  1815. llama_context_params params) {
  1816. if (!model) {
  1817. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  1818. return nullptr;
  1819. }
  1820. if (params.n_batch == 0 && params.n_ubatch == 0) {
  1821. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  1822. return nullptr;
  1823. }
  1824. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  1825. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  1826. return nullptr;
  1827. }
  1828. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  1829. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  1830. params.flash_attn = false;
  1831. }
  1832. if (ggml_is_quantized(params.type_v) && !params.flash_attn) {
  1833. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  1834. return nullptr;
  1835. }
  1836. try {
  1837. auto * ctx = new llama_context(*model, params);
  1838. return ctx;
  1839. } catch (const std::exception & err) {
  1840. LLAMA_LOG_ERROR("%s: failed to initialize the context: %s\n", __func__, err.what());
  1841. }
  1842. return nullptr;
  1843. }
  1844. // deprecated
  1845. llama_context * llama_new_context_with_model(
  1846. llama_model * model,
  1847. llama_context_params params) {
  1848. return llama_init_from_model(model, params);
  1849. }
  1850. void llama_free(llama_context * ctx) {
  1851. delete ctx;
  1852. }
  1853. uint32_t llama_n_ctx(const llama_context * ctx) {
  1854. return ctx->n_ctx();
  1855. }
  1856. uint32_t llama_n_batch(const llama_context * ctx) {
  1857. return ctx->n_batch();
  1858. }
  1859. uint32_t llama_n_ubatch(const llama_context * ctx) {
  1860. return ctx->n_ubatch();
  1861. }
  1862. uint32_t llama_n_seq_max(const llama_context * ctx) {
  1863. return ctx->n_seq_max();
  1864. }
  1865. const llama_model * llama_get_model(const llama_context * ctx) {
  1866. return &ctx->get_model();
  1867. }
  1868. // deprecated
  1869. llama_kv_cache * llama_get_kv_self(llama_context * ctx) {
  1870. return dynamic_cast<llama_kv_cache *>(ctx->get_memory());
  1871. }
  1872. // deprecated
  1873. void llama_kv_self_update(llama_context * ctx) {
  1874. ctx->kv_self_update(false);
  1875. }
  1876. enum llama_pooling_type llama_pooling_type(const llama_context * ctx) {
  1877. return ctx->pooling_type();
  1878. }
  1879. void llama_attach_threadpool(
  1880. llama_context * ctx,
  1881. ggml_threadpool_t threadpool,
  1882. ggml_threadpool_t threadpool_batch) {
  1883. ctx->attach_threadpool(threadpool, threadpool_batch);
  1884. }
  1885. void llama_detach_threadpool(llama_context * ctx) {
  1886. ctx->detach_threadpool();
  1887. }
  1888. void llama_set_n_threads(llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
  1889. ctx->set_n_threads(n_threads, n_threads_batch);
  1890. }
  1891. int32_t llama_n_threads(llama_context * ctx) {
  1892. return ctx->n_threads();
  1893. }
  1894. int32_t llama_n_threads_batch(llama_context * ctx) {
  1895. return ctx->n_threads_batch();
  1896. }
  1897. void llama_set_abort_callback(llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  1898. ctx->set_abort_callback(abort_callback, abort_callback_data);
  1899. }
  1900. void llama_set_embeddings(llama_context * ctx, bool embeddings) {
  1901. ctx->set_embeddings(embeddings);
  1902. }
  1903. void llama_set_causal_attn(llama_context * ctx, bool causal_attn) {
  1904. ctx->set_causal_attn(causal_attn);
  1905. }
  1906. void llama_set_warmup(llama_context * ctx, bool warmup) {
  1907. ctx->set_warmup(warmup);
  1908. }
  1909. void llama_synchronize(llama_context * ctx) {
  1910. ctx->synchronize();
  1911. }
  1912. float * llama_get_logits(llama_context * ctx) {
  1913. ctx->synchronize();
  1914. return ctx->get_logits();
  1915. }
  1916. float * llama_get_logits_ith(llama_context * ctx, int32_t i) {
  1917. ctx->synchronize();
  1918. return ctx->get_logits_ith(i);
  1919. }
  1920. float * llama_get_embeddings(llama_context * ctx) {
  1921. ctx->synchronize();
  1922. return ctx->get_embeddings();
  1923. }
  1924. float * llama_get_embeddings_ith(llama_context * ctx, int32_t i) {
  1925. ctx->synchronize();
  1926. return ctx->get_embeddings_ith(i);
  1927. }
  1928. float * llama_get_embeddings_seq(llama_context * ctx, llama_seq_id seq_id) {
  1929. ctx->synchronize();
  1930. return ctx->get_embeddings_seq(seq_id);
  1931. }
  1932. // llama adapter API
  1933. int32_t llama_set_adapter_lora(
  1934. llama_context * ctx,
  1935. llama_adapter_lora * adapter,
  1936. float scale) {
  1937. ctx->set_adapter_lora(adapter, scale);
  1938. return 0;
  1939. }
  1940. int32_t llama_rm_adapter_lora(
  1941. llama_context * ctx,
  1942. llama_adapter_lora * adapter) {
  1943. bool res = ctx->rm_adapter_lora(adapter);
  1944. return res ? 0 : -1;
  1945. }
  1946. void llama_clear_adapter_lora(llama_context * ctx) {
  1947. ctx->clear_adapter_lora();
  1948. }
  1949. int32_t llama_apply_adapter_cvec(
  1950. llama_context * ctx,
  1951. const float * data,
  1952. size_t len,
  1953. int32_t n_embd,
  1954. int32_t il_start,
  1955. int32_t il_end) {
  1956. bool res = ctx->apply_adapter_cvec(data, len, n_embd, il_start, il_end);
  1957. return res ? 0 : -1;
  1958. }
  1959. //
  1960. // memory
  1961. //
  1962. llama_memory_t llama_get_memory(const struct llama_context * ctx) {
  1963. return ctx->get_memory();
  1964. }
  1965. void llama_memory_clear(llama_memory_t mem, bool data) {
  1966. if (!mem) {
  1967. return;
  1968. }
  1969. mem->clear(data);
  1970. }
  1971. bool llama_memory_seq_rm(
  1972. llama_memory_t mem,
  1973. llama_seq_id seq_id,
  1974. llama_pos p0,
  1975. llama_pos p1) {
  1976. if (!mem) {
  1977. return true;
  1978. }
  1979. return mem->seq_rm(seq_id, p0, p1);
  1980. }
  1981. void llama_memory_seq_cp(
  1982. llama_memory_t mem,
  1983. llama_seq_id seq_id_src,
  1984. llama_seq_id seq_id_dst,
  1985. llama_pos p0,
  1986. llama_pos p1) {
  1987. if (!mem) {
  1988. return;
  1989. }
  1990. mem->seq_cp(seq_id_src, seq_id_dst, p0, p1);
  1991. }
  1992. void llama_memory_seq_keep(
  1993. llama_memory_t mem,
  1994. llama_seq_id seq_id) {
  1995. if (!mem) {
  1996. return;
  1997. }
  1998. mem->seq_keep(seq_id);
  1999. }
  2000. void llama_memory_seq_add(
  2001. llama_memory_t mem,
  2002. llama_seq_id seq_id,
  2003. llama_pos p0,
  2004. llama_pos p1,
  2005. llama_pos delta) {
  2006. if (!mem) {
  2007. return;
  2008. }
  2009. mem->seq_add(seq_id, p0, p1, delta);
  2010. }
  2011. void llama_memory_seq_div(
  2012. llama_memory_t mem,
  2013. llama_seq_id seq_id,
  2014. llama_pos p0,
  2015. llama_pos p1,
  2016. int d) {
  2017. if (!mem) {
  2018. return;
  2019. }
  2020. mem->seq_div(seq_id, p0, p1, d);
  2021. }
  2022. llama_pos llama_memory_seq_pos_min(
  2023. llama_memory_t mem,
  2024. llama_seq_id seq_id) {
  2025. if (!mem) {
  2026. return -1;
  2027. }
  2028. return mem->seq_pos_min(seq_id);
  2029. }
  2030. llama_pos llama_memory_seq_pos_max(
  2031. llama_memory_t mem,
  2032. llama_seq_id seq_id) {
  2033. if (!mem) {
  2034. return -1;
  2035. }
  2036. return mem->seq_pos_max(seq_id);
  2037. }
  2038. bool llama_memory_can_shift(llama_memory_t mem) {
  2039. if (!mem) {
  2040. return false;
  2041. }
  2042. return mem->get_can_shift();
  2043. }
  2044. //
  2045. // kv cache
  2046. //
  2047. // deprecated
  2048. int32_t llama_kv_self_n_tokens(const llama_context * ctx) {
  2049. const auto * kv = llama_get_memory(ctx);
  2050. if (!kv) {
  2051. return 0;
  2052. }
  2053. int32_t res = 0;
  2054. for (uint32_t s = 0; s < ctx->get_cparams().n_seq_max; s++) {
  2055. const llama_pos p0 = kv->seq_pos_min(s);
  2056. const llama_pos p1 = kv->seq_pos_max(s);
  2057. if (p0 >= 0) {
  2058. res += (p1 - p0) + 1;
  2059. }
  2060. }
  2061. return res;
  2062. }
  2063. // deprecated
  2064. // note: this is the same as above - will be removed anyway, so it's ok
  2065. int32_t llama_kv_self_used_cells(const llama_context * ctx) {
  2066. const auto * kv = llama_get_memory(ctx);
  2067. if (!kv) {
  2068. return 0;
  2069. }
  2070. int32_t res = 0;
  2071. for (uint32_t s = 0; s < ctx->get_cparams().n_seq_max; s++) {
  2072. const llama_pos p0 = kv->seq_pos_min(s);
  2073. const llama_pos p1 = kv->seq_pos_max(s);
  2074. if (p0 >= 0) {
  2075. res += (p1 - p0) + 1;
  2076. }
  2077. }
  2078. return res;
  2079. }
  2080. // deprecated
  2081. void llama_kv_self_clear(llama_context * ctx) {
  2082. auto * kv = llama_get_memory(ctx);
  2083. if (!kv) {
  2084. return;
  2085. }
  2086. llama_memory_clear(kv, true);
  2087. }
  2088. // deprecated
  2089. bool llama_kv_self_seq_rm(
  2090. llama_context * ctx,
  2091. llama_seq_id seq_id,
  2092. llama_pos p0,
  2093. llama_pos p1) {
  2094. auto * kv = llama_get_memory(ctx);
  2095. if (!kv) {
  2096. return true;
  2097. }
  2098. return llama_memory_seq_rm(kv, seq_id, p0, p1);
  2099. }
  2100. // deprecated
  2101. void llama_kv_self_seq_cp(
  2102. llama_context * ctx,
  2103. llama_seq_id seq_id_src,
  2104. llama_seq_id seq_id_dst,
  2105. llama_pos p0,
  2106. llama_pos p1) {
  2107. auto * kv = llama_get_memory(ctx);
  2108. if (!kv) {
  2109. return;
  2110. }
  2111. llama_memory_seq_cp(kv, seq_id_src, seq_id_dst, p0, p1);
  2112. }
  2113. // deprecated
  2114. void llama_kv_self_seq_keep(llama_context * ctx, llama_seq_id seq_id) {
  2115. auto * kv = llama_get_memory(ctx);
  2116. if (!kv) {
  2117. return;
  2118. }
  2119. llama_memory_seq_keep(kv, seq_id);
  2120. }
  2121. // deprecated
  2122. void llama_kv_self_seq_add(
  2123. llama_context * ctx,
  2124. llama_seq_id seq_id,
  2125. llama_pos p0,
  2126. llama_pos p1,
  2127. llama_pos delta) {
  2128. auto * kv = llama_get_memory(ctx);
  2129. if (!kv) {
  2130. return;
  2131. }
  2132. llama_memory_seq_add(kv, seq_id, p0, p1, delta);
  2133. }
  2134. // deprecated
  2135. void llama_kv_self_seq_div(
  2136. llama_context * ctx,
  2137. llama_seq_id seq_id,
  2138. llama_pos p0,
  2139. llama_pos p1,
  2140. int d) {
  2141. auto * kv = llama_get_memory(ctx);
  2142. if (!kv) {
  2143. return;
  2144. }
  2145. llama_memory_seq_div(kv, seq_id, p0, p1, d);
  2146. }
  2147. // deprecated
  2148. llama_pos llama_kv_self_seq_pos_min(llama_context * ctx, llama_seq_id seq_id) {
  2149. auto * kv = llama_get_memory(ctx);
  2150. if (!kv) {
  2151. return -1;
  2152. }
  2153. return llama_memory_seq_pos_min(kv, seq_id);
  2154. }
  2155. // deprecated
  2156. llama_pos llama_kv_self_seq_pos_max(llama_context * ctx, llama_seq_id seq_id) {
  2157. auto * kv = llama_get_memory(ctx);
  2158. if (!kv) {
  2159. return -1;
  2160. }
  2161. return llama_memory_seq_pos_max(kv, seq_id);
  2162. }
  2163. // deprecated
  2164. void llama_kv_self_defrag(llama_context * ctx) {
  2165. // force defrag
  2166. ctx->kv_self_defrag_sched();
  2167. }
  2168. // deprecated
  2169. bool llama_kv_self_can_shift(const llama_context * ctx) {
  2170. auto * kv = llama_get_memory(ctx);
  2171. if (!kv) {
  2172. return false;
  2173. }
  2174. return llama_memory_can_shift(kv);
  2175. }
  2176. // llama state API
  2177. // deprecated
  2178. size_t llama_get_state_size(llama_context * ctx) {
  2179. return llama_state_get_size(ctx);
  2180. }
  2181. // deprecated
  2182. size_t llama_copy_state_data(llama_context * ctx, uint8_t * dst) {
  2183. return llama_state_get_data(ctx, dst, -1);
  2184. }
  2185. // deprecated
  2186. size_t llama_set_state_data(llama_context * ctx, const uint8_t * src) {
  2187. return llama_state_set_data(ctx, src, -1);
  2188. }
  2189. // deprecated
  2190. 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) {
  2191. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  2192. }
  2193. // deprecated
  2194. bool llama_save_session_file(llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  2195. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  2196. }
  2197. // Returns the *actual* size of the state.
  2198. // Intended to be used when saving to state to a buffer.
  2199. size_t llama_state_get_size(llama_context * ctx) {
  2200. return ctx->state_get_size();
  2201. }
  2202. size_t llama_state_get_data(llama_context * ctx, uint8_t * dst, size_t size) {
  2203. ctx->synchronize();
  2204. return ctx->state_get_data(dst, size);
  2205. }
  2206. // Sets the state reading from the specified source address
  2207. size_t llama_state_set_data(llama_context * ctx, const uint8_t * src, size_t size) {
  2208. ctx->synchronize();
  2209. return ctx->state_set_data(src, size);
  2210. }
  2211. 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) {
  2212. ctx->synchronize();
  2213. try {
  2214. return ctx->state_load_file(path_session, tokens_out, n_token_capacity, n_token_count_out);
  2215. } catch (const std::exception & err) {
  2216. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  2217. return false;
  2218. }
  2219. }
  2220. bool llama_state_save_file(llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  2221. ctx->synchronize();
  2222. try {
  2223. return ctx->state_save_file(path_session, tokens, n_token_count);
  2224. } catch (const std::exception & err) {
  2225. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  2226. return false;
  2227. }
  2228. }
  2229. size_t llama_state_seq_get_size(llama_context * ctx, llama_seq_id seq_id) {
  2230. return llama_state_seq_get_size_ext(ctx, seq_id, 0);
  2231. }
  2232. size_t llama_state_seq_get_data(llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  2233. return llama_state_seq_get_data_ext(ctx, dst, size, seq_id, 0);
  2234. }
  2235. size_t llama_state_seq_set_data(llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id seq_id) {
  2236. return llama_state_seq_set_data_ext(ctx, src, size, seq_id, 0);
  2237. }
  2238. size_t llama_state_seq_get_size_ext(llama_context * ctx, llama_seq_id seq_id, llama_state_seq_flags flags) {
  2239. return ctx->state_seq_get_size(seq_id, flags);
  2240. }
  2241. 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) {
  2242. ctx->synchronize();
  2243. return ctx->state_seq_get_data(seq_id, dst, size, flags);
  2244. }
  2245. 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) {
  2246. ctx->synchronize();
  2247. return ctx->state_seq_set_data(seq_id, src, size, flags);
  2248. }
  2249. 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) {
  2250. ctx->synchronize();
  2251. try {
  2252. return ctx->state_seq_save_file(seq_id, filepath, tokens, n_token_count);
  2253. } catch (const std::exception & err) {
  2254. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  2255. return 0;
  2256. }
  2257. }
  2258. 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) {
  2259. ctx->synchronize();
  2260. try {
  2261. return ctx->state_seq_load_file(dest_seq_id, filepath, tokens_out, n_token_capacity, n_token_count_out);
  2262. } catch (const std::exception & err) {
  2263. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  2264. return 0;
  2265. }
  2266. }
  2267. ///
  2268. int32_t llama_encode(
  2269. llama_context * ctx,
  2270. llama_batch batch) {
  2271. const int ret = ctx->encode(batch);
  2272. if (ret != 0) {
  2273. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  2274. }
  2275. return ret;
  2276. }
  2277. int32_t llama_decode(
  2278. llama_context * ctx,
  2279. llama_batch batch) {
  2280. const int ret = ctx->decode(batch);
  2281. if (ret != 0 && ret != 1) {
  2282. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  2283. }
  2284. return ret;
  2285. }
  2286. //
  2287. // perf
  2288. //
  2289. llama_perf_context_data llama_perf_context(const llama_context * ctx) {
  2290. llama_perf_context_data data = {};
  2291. if (ctx == nullptr) {
  2292. return data;
  2293. }
  2294. data = ctx->perf_get_data();
  2295. return data;
  2296. }
  2297. void llama_perf_context_print(const llama_context * ctx) {
  2298. const auto data = llama_perf_context(ctx);
  2299. const double t_end_ms = 1e-3 * ggml_time_us();
  2300. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
  2301. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  2302. __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);
  2303. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  2304. __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
  2305. 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));
  2306. LLAMA_LOG_INFO("%s: graphs reused = %10d\n", __func__, data.n_reused);
  2307. }
  2308. void llama_perf_context_reset(llama_context * ctx) {
  2309. ctx->perf_reset();
  2310. }
  2311. //
  2312. // training
  2313. //
  2314. bool llama_opt_param_filter_all(const struct ggml_tensor * tensor, void * userdata) {
  2315. GGML_UNUSED(tensor);
  2316. GGML_UNUSED(userdata);
  2317. return true;
  2318. }
  2319. void llama_opt_init(struct llama_context * ctx, struct llama_model * model, struct llama_opt_params lopt_params) {
  2320. ctx->opt_init(model, lopt_params);
  2321. }
  2322. void llama_opt_epoch(
  2323. struct llama_context * ctx,
  2324. ggml_opt_dataset_t dataset,
  2325. ggml_opt_result_t result_train,
  2326. ggml_opt_result_t result_eval,
  2327. int64_t idata_split,
  2328. ggml_opt_epoch_callback callback_train,
  2329. ggml_opt_epoch_callback callback_eval) {
  2330. ctx->opt_epoch(
  2331. dataset,
  2332. result_train,
  2333. result_eval,
  2334. idata_split,
  2335. callback_train,
  2336. callback_eval);
  2337. }