llama-context.cpp 88 KB

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