llama-context.cpp 92 KB

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