llama-context.cpp 93 KB

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