llama-context.cpp 92 KB

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