llama-context.cpp 92 KB

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