llama-context.cpp 100 KB

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