llama-context.cpp 78 KB

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