llama-context.cpp 91 KB

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