llama-context.cpp 92 KB

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