llama-context.cpp 93 KB

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