llama-context.cpp 94 KB

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