llama-graph.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114
  1. #include "llama-graph.h"
  2. #include "llama-impl.h"
  3. #include "llama-batch.h"
  4. #include "llama-cparams.h"
  5. #include "llama-kv-cache.h"
  6. #include "llama-kv-cache-iswa.h"
  7. #include "llama-memory-hybrid.h"
  8. #include "llama-memory-recurrent.h"
  9. #include <cassert>
  10. #include <cmath>
  11. #include <cstring>
  12. void llm_graph_input_embd::set_input(const llama_ubatch * ubatch) {
  13. if (ubatch->token) {
  14. const int64_t n_tokens = ubatch->n_tokens;
  15. ggml_backend_tensor_set(tokens, ubatch->token, 0, n_tokens*ggml_element_size(tokens));
  16. }
  17. if (ubatch->embd) {
  18. const int64_t n_embd = embd->ne[0];
  19. const int64_t n_tokens = ubatch->n_tokens;
  20. ggml_backend_tensor_set(embd, ubatch->embd, 0, n_tokens*n_embd*ggml_element_size(embd));
  21. }
  22. }
  23. bool llm_graph_input_embd::can_reuse(const llm_graph_params & params) {
  24. bool res = true;
  25. res &= (!tokens && !params.ubatch.token) || (tokens && tokens->ne[0] == params.ubatch.n_tokens);
  26. res &= (!embd && !params.ubatch.embd) || (embd && embd->ne[0] == params.ubatch.n_tokens);
  27. return res;
  28. }
  29. void llm_graph_input_pos::set_input(const llama_ubatch * ubatch) {
  30. if (ubatch->pos && pos) {
  31. const int64_t n_tokens = ubatch->n_tokens;
  32. if (ubatch->token && n_pos_per_embd == 4) {
  33. // in case we're using M-RoPE with text tokens, convert the 1D positions to 4D
  34. // the 3 first dims are the same, and 4th dim is all 0
  35. std::vector<llama_pos> pos_data(n_tokens*n_pos_per_embd);
  36. // copy the first dimension
  37. for (int i = 0; i < n_tokens; ++i) {
  38. pos_data[ i] = ubatch->pos[i];
  39. pos_data[ n_tokens + i] = ubatch->pos[i];
  40. pos_data[2 * n_tokens + i] = ubatch->pos[i];
  41. pos_data[3 * n_tokens + i] = 0; // 4th dim is 0
  42. }
  43. ggml_backend_tensor_set(pos, pos_data.data(), 0, pos_data.size()*ggml_element_size(pos));
  44. } else {
  45. ggml_backend_tensor_set(pos, ubatch->pos, 0, n_tokens*n_pos_per_embd*ggml_element_size(pos));
  46. }
  47. }
  48. }
  49. bool llm_graph_input_pos::can_reuse(const llm_graph_params & params) {
  50. bool res = true;
  51. res &= pos->ne[0] == params.ubatch.n_tokens;
  52. return res;
  53. }
  54. void llm_graph_input_attn_temp::set_input(const llama_ubatch * ubatch) {
  55. if (ubatch->pos && attn_scale) {
  56. const int64_t n_tokens = ubatch->n_tokens;
  57. GGML_ASSERT(f_attn_temp_scale != 0.0f);
  58. GGML_ASSERT(n_attn_temp_floor_scale != 0);
  59. std::vector<float> attn_scale_data(n_tokens, 0.0f);
  60. for (int i = 0; i < n_tokens; ++i) {
  61. const float pos = ubatch->pos[i];
  62. attn_scale_data[i] = std::log(
  63. std::floor((pos + f_attn_temp_offset) / n_attn_temp_floor_scale) + 1.0
  64. ) * f_attn_temp_scale + 1.0;
  65. }
  66. ggml_backend_tensor_set(attn_scale, attn_scale_data.data(), 0, n_tokens*ggml_element_size(attn_scale));
  67. }
  68. }
  69. void llm_graph_input_pos_bucket::set_input(const llama_ubatch * ubatch) {
  70. if (pos_bucket) {
  71. const int64_t n_tokens = ubatch->n_tokens;
  72. GGML_ASSERT(ggml_backend_buffer_is_host(pos_bucket->buffer));
  73. GGML_ASSERT(!ubatch->equal_seqs()); // TODO: use ubatch->n_seqs instead of failing
  74. int32_t * data = (int32_t *) pos_bucket->data;
  75. for (int h = 0; h < 1; ++h) {
  76. for (int j = 0; j < n_tokens; ++j) {
  77. for (int i = 0; i < n_tokens; ++i) {
  78. data[h*(n_tokens*n_tokens) + j*n_tokens + i] = llama_relative_position_bucket(ubatch->pos[i], ubatch->pos[j], hparams.n_rel_attn_bkts, true);
  79. }
  80. }
  81. }
  82. }
  83. }
  84. void llm_graph_input_pos_bucket_kv::set_input(const llama_ubatch * ubatch) {
  85. if (pos_bucket) {
  86. mctx->set_input_pos_bucket(pos_bucket, ubatch);
  87. }
  88. }
  89. void llm_graph_input_out_ids::set_input(const llama_ubatch * ubatch) {
  90. GGML_ASSERT(out_ids);
  91. const int64_t n_tokens = ubatch->n_tokens;
  92. GGML_ASSERT(ggml_backend_buffer_is_host(out_ids->buffer));
  93. int32_t * data = (int32_t *) out_ids->data;
  94. if (n_outputs == n_tokens) {
  95. for (int i = 0; i < n_tokens; ++i) {
  96. data[i] = i;
  97. }
  98. return;
  99. }
  100. GGML_ASSERT(ubatch->output);
  101. int n_outputs = 0;
  102. for (int i = 0; i < n_tokens; ++i) {
  103. if (ubatch->output[i]) {
  104. data[n_outputs++] = i;
  105. }
  106. }
  107. }
  108. bool llm_graph_input_out_ids::can_reuse(const llm_graph_params & params) {
  109. bool res = true;
  110. res &= n_outputs == params.n_outputs;
  111. return res;
  112. }
  113. void llm_graph_input_mean::set_input(const llama_ubatch * ubatch) {
  114. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  115. const int64_t n_tokens = ubatch->n_tokens;
  116. const int64_t n_seq_tokens = ubatch->n_seq_tokens;
  117. const int64_t n_seqs_unq = ubatch->n_seqs_unq;
  118. GGML_ASSERT(mean);
  119. GGML_ASSERT(ggml_backend_buffer_is_host(mean->buffer));
  120. float * data = (float *) mean->data;
  121. memset(mean->data, 0, n_tokens*n_seqs_unq*ggml_element_size(mean));
  122. std::vector<uint64_t> sums(n_seqs_unq, 0);
  123. for (int i = 0; i < n_tokens; i += n_seq_tokens) {
  124. for (int s = 0; s < ubatch->n_seq_id[i]; ++s) {
  125. const llama_seq_id seq_id = ubatch->seq_id[i][s];
  126. const int32_t seq_idx = ubatch->seq_idx[seq_id];
  127. sums[seq_idx] += ubatch->n_seq_tokens;
  128. }
  129. }
  130. std::vector<float> div(n_seqs_unq, 0.0f);
  131. for (int s = 0; s < n_seqs_unq; ++s) {
  132. const uint64_t sum = sums[s];
  133. if (sum > 0) {
  134. div[s] = 1.0f/float(sum);
  135. }
  136. }
  137. for (int i = 0; i < n_tokens; i += n_seq_tokens) {
  138. for (int s = 0; s < ubatch->n_seq_id[i]; ++s) {
  139. const llama_seq_id seq_id = ubatch->seq_id[i][s];
  140. const int32_t seq_idx = ubatch->seq_idx[seq_id];
  141. for (int j = 0; j < n_seq_tokens; ++j) {
  142. data[seq_idx*n_tokens + i + j] = div[seq_idx];
  143. }
  144. }
  145. }
  146. }
  147. }
  148. void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) {
  149. const int64_t n_tokens = ubatch->n_tokens;
  150. const int64_t n_seqs_unq = ubatch->n_seqs_unq;
  151. if (cparams.embeddings && (
  152. cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
  153. cparams.pooling_type == LLAMA_POOLING_TYPE_RANK ||
  154. cparams.pooling_type == LLAMA_POOLING_TYPE_LAST
  155. )) {
  156. GGML_ASSERT(cls);
  157. GGML_ASSERT(ggml_backend_buffer_is_host(cls->buffer));
  158. uint32_t * data = (uint32_t *) cls->data;
  159. memset(cls->data, 0, n_seqs_unq*ggml_element_size(cls));
  160. std::vector<int> target_pos(n_seqs_unq, -1);
  161. std::vector<int> target_row(n_seqs_unq, -1);
  162. const bool last = (
  163. cparams.pooling_type == LLAMA_POOLING_TYPE_LAST ||
  164. (cparams.pooling_type == LLAMA_POOLING_TYPE_RANK && arch == LLM_ARCH_QWEN3) // qwen3 reranking & embedding models use last token
  165. );
  166. for (int i = 0; i < n_tokens; ++i) {
  167. const llama_pos pos = ubatch->pos[i];
  168. for (int s = 0; s < ubatch->n_seq_id[i]; ++s) {
  169. const llama_seq_id seq_id = ubatch->seq_id[i][s];
  170. const int32_t seq_idx = ubatch->seq_idx[seq_id];
  171. if (
  172. (target_pos[seq_idx] == -1) ||
  173. ( last && pos >= target_pos[seq_idx]) ||
  174. (!last && pos < target_pos[seq_idx])
  175. ) {
  176. target_pos[seq_idx] = pos;
  177. target_row[seq_idx] = i;
  178. }
  179. }
  180. }
  181. for (int s = 0; s < n_seqs_unq; ++s) {
  182. if (target_row[s] >= 0) {
  183. data[s] = target_row[s];
  184. }
  185. }
  186. }
  187. }
  188. void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) {
  189. GGML_UNUSED(ubatch);
  190. const int64_t n_rs = mctx->get_n_rs();
  191. if (s_copy) {
  192. GGML_ASSERT(ggml_backend_buffer_is_host(s_copy->buffer));
  193. int32_t * data = (int32_t *) s_copy->data;
  194. // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
  195. for (uint32_t i = 0; i < n_rs; ++i) {
  196. data[i] = mctx->s_copy(i);
  197. }
  198. }
  199. }
  200. bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) {
  201. const auto * mctx = static_cast<const llama_memory_recurrent_context *>(params.mctx);
  202. this->mctx = mctx;
  203. bool res = true;
  204. res &= s_copy->ne[0] == mctx->get_n_rs();
  205. res &= s_copy_main->ne[0] == params.ubatch.n_seqs;
  206. res &= s_copy_extra->ne[0] == mctx->get_n_rs() - params.ubatch.n_seqs;
  207. res &= head == mctx->get_head();
  208. res &= rs_z == mctx->get_rs_z();
  209. return res;
  210. }
  211. void llm_graph_input_cross_embd::set_input(const llama_ubatch * ubatch) {
  212. GGML_UNUSED(ubatch);
  213. if (cross_embd && !cross->v_embd.empty()) {
  214. assert(cross_embd->type == GGML_TYPE_F32);
  215. ggml_backend_tensor_set(cross_embd, cross->v_embd.data(), 0, ggml_nbytes(cross_embd));
  216. }
  217. }
  218. static void print_mask(const float * data, int64_t n_tokens, int64_t n_kv, int64_t n_swa, llama_swa_type swa_type) {
  219. LLAMA_LOG_DEBUG("%s: === Attention mask ===\n", __func__);
  220. const char * swa_type_str = "unknown";
  221. switch (swa_type) {
  222. case LLAMA_SWA_TYPE_NONE: swa_type_str = "LLAMA_SWA_TYPE_NONE"; break;
  223. case LLAMA_SWA_TYPE_STANDARD: swa_type_str = "LLAMA_SWA_TYPE_STANDARD"; break;
  224. case LLAMA_SWA_TYPE_CHUNKED: swa_type_str = "LLAMA_SWA_TYPE_CHUNKED"; break;
  225. case LLAMA_SWA_TYPE_SYMMETRIC: swa_type_str = "LLAMA_SWA_TYPE_SYMMETRIC"; break;
  226. };
  227. LLAMA_LOG_DEBUG("%s: n_swa : %d, n_kv: %d, swq_type: %s\n", __func__, (int)n_swa, (int)n_kv, swa_type_str);
  228. LLAMA_LOG_DEBUG("%s: '0' = can attend, '∞' = masked\n", __func__);
  229. LLAMA_LOG_DEBUG("%s: Rows = query tokens, Columns = key/value tokens\n\n", __func__);
  230. LLAMA_LOG_DEBUG(" ");
  231. for (int j = 0; j < std::min((int64_t)20, n_kv); ++j) {
  232. LLAMA_LOG_DEBUG("%2d", j);
  233. }
  234. LLAMA_LOG_DEBUG("\n");
  235. for (int i = 0; i < std::min((int64_t)20, n_tokens); ++i) {
  236. LLAMA_LOG_DEBUG(" %2d ", i);
  237. for (int j = 0; j < std::min((int64_t)20, n_kv); ++j) {
  238. float val = data[i * n_kv + j];
  239. if (val == -INFINITY) {
  240. LLAMA_LOG_DEBUG(" ∞");
  241. } else {
  242. LLAMA_LOG_DEBUG(" 0");
  243. }
  244. }
  245. LLAMA_LOG_DEBUG("\n");
  246. }
  247. }
  248. void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) {
  249. const int64_t n_kv = ubatch->n_tokens;
  250. const int64_t n_tokens = ubatch->n_tokens;
  251. const auto fill_mask = [&](float * data, int n_swa, llama_swa_type swa_type) {
  252. for (int h = 0; h < 1; ++h) {
  253. for (int i1 = 0; i1 < n_tokens; ++i1) {
  254. const llama_seq_id s1 = ubatch->seq_id[i1][0];
  255. const llama_pos p1 = ubatch->pos[i1];
  256. const uint64_t idst = h*(n_kv*n_tokens) + i1*n_kv;
  257. for (int i0 = 0; i0 < n_tokens; ++i0) {
  258. const llama_seq_id s0 = ubatch->seq_id[i0][0];
  259. const llama_pos p0 = ubatch->pos[i0];
  260. // mask different sequences
  261. if (s0 != s1) {
  262. continue;
  263. }
  264. // mask future tokens
  265. if (cparams.causal_attn && p0 > p1) {
  266. continue;
  267. }
  268. // apply SWA if any
  269. if (llama_hparams::is_masked_swa(n_swa, swa_type, p0, p1)) {
  270. continue;
  271. }
  272. data[idst + i0] = hparams.use_alibi ? -std::abs(p0 - p1) : 0.0f;
  273. }
  274. }
  275. }
  276. };
  277. {
  278. GGML_ASSERT(self_kq_mask);
  279. GGML_ASSERT(ggml_backend_buffer_is_host(self_kq_mask->buffer));
  280. float * data = (float *) self_kq_mask->data;
  281. std::fill(data, data + ggml_nelements(self_kq_mask), -INFINITY);
  282. fill_mask(data, 0, LLAMA_SWA_TYPE_NONE);
  283. if (debug) {
  284. print_mask(data, n_tokens, n_kv, 0, LLAMA_SWA_TYPE_NONE);
  285. }
  286. }
  287. if (hparams.swa_type != LLAMA_SWA_TYPE_NONE) {
  288. GGML_ASSERT(self_kq_mask_swa);
  289. GGML_ASSERT(ggml_backend_buffer_is_host(self_kq_mask_swa->buffer));
  290. float * data = (float *) self_kq_mask_swa->data;
  291. std::fill(data, data + ggml_nelements(self_kq_mask_swa), -INFINITY);
  292. fill_mask(data, hparams.n_swa, hparams.swa_type);
  293. if (debug) {
  294. print_mask(data, n_tokens, n_kv, hparams.n_swa, hparams.swa_type);
  295. }
  296. }
  297. }
  298. void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) {
  299. mctx->set_input_k_idxs(self_k_idxs, ubatch);
  300. mctx->set_input_v_idxs(self_v_idxs, ubatch);
  301. mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn);
  302. }
  303. bool llm_graph_input_attn_kv::can_reuse(const llm_graph_params & params) {
  304. const auto * mctx = static_cast<const llama_kv_cache_context *>(params.mctx);
  305. this->mctx = mctx;
  306. bool res = true;
  307. res &= self_k_idxs->ne[0] == params.ubatch.n_tokens;
  308. //res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there
  309. res &= self_kq_mask->ne[0] == mctx->get_n_kv();
  310. res &= self_kq_mask->ne[1] == params.ubatch.n_tokens;
  311. return res;
  312. }
  313. void llm_graph_input_attn_kv_iswa::set_input(const llama_ubatch * ubatch) {
  314. mctx->get_base()->set_input_k_idxs(self_k_idxs, ubatch);
  315. mctx->get_base()->set_input_v_idxs(self_v_idxs, ubatch);
  316. mctx->get_base()->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn);
  317. mctx->get_swa()->set_input_k_idxs(self_k_idxs_swa, ubatch);
  318. mctx->get_swa()->set_input_v_idxs(self_v_idxs_swa, ubatch);
  319. mctx->get_swa()->set_input_kq_mask(self_kq_mask_swa, ubatch, cparams.causal_attn);
  320. }
  321. bool llm_graph_input_attn_kv_iswa::can_reuse(const llm_graph_params & params) {
  322. const auto * mctx = static_cast<const llama_kv_cache_iswa_context *>(params.mctx);
  323. this->mctx = mctx;
  324. bool res = true;
  325. res &= self_k_idxs->ne[0] == params.ubatch.n_tokens;
  326. //res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there
  327. res &= self_k_idxs_swa->ne[0] == params.ubatch.n_tokens;
  328. //res &= self_v_idxs_swa->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there
  329. res &= self_kq_mask->ne[0] == mctx->get_base()->get_n_kv();
  330. res &= self_kq_mask->ne[1] == params.ubatch.n_tokens;
  331. res &= self_kq_mask_swa->ne[0] == mctx->get_swa()->get_n_kv();
  332. res &= self_kq_mask_swa->ne[1] == params.ubatch.n_tokens;
  333. return res;
  334. }
  335. void llm_graph_input_attn_cross::set_input(const llama_ubatch * ubatch) {
  336. GGML_ASSERT(cross_kq_mask);
  337. const int64_t n_enc = cross_kq_mask->ne[0];
  338. const int64_t n_tokens = ubatch->n_tokens;
  339. GGML_ASSERT(ggml_backend_buffer_is_host(cross_kq_mask->buffer));
  340. GGML_ASSERT(!ubatch->equal_seqs()); // TODO: use ubatch->n_seqs instead of failing
  341. float * data = (float *) cross_kq_mask->data;
  342. for (int h = 0; h < 1; ++h) {
  343. for (int i = 0; i < n_tokens; ++i) {
  344. for (int j = 0; j < n_enc; ++j) {
  345. float f = -INFINITY;
  346. for (int s = 0; s < ubatch->n_seq_id[i]; ++s) {
  347. const llama_seq_id seq_id = ubatch->seq_id[i][s];
  348. if (cross->seq_ids_enc[j].find(seq_id) != cross->seq_ids_enc[j].end()) {
  349. f = 0.0f;
  350. }
  351. }
  352. data[h*(n_enc*n_tokens) + i*n_enc + j] = f;
  353. }
  354. }
  355. for (int i = n_tokens; i < n_tokens; ++i) {
  356. for (int j = 0; j < n_enc; ++j) {
  357. data[h*(n_enc*n_tokens) + i*n_enc + j] = -INFINITY;
  358. }
  359. }
  360. }
  361. }
  362. void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) {
  363. mctx->get_attn()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch);
  364. mctx->get_attn()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch);
  365. mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn);
  366. const int64_t n_rs = mctx->get_recr()->get_n_rs();
  367. if (inp_rs->s_copy) {
  368. GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer));
  369. int32_t * data = (int32_t *) inp_rs->s_copy->data;
  370. // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
  371. for (uint32_t i = 0; i < n_rs; ++i) {
  372. data[i] = mctx->get_recr()->s_copy(i);
  373. }
  374. }
  375. }
  376. bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) {
  377. const auto * mctx = static_cast<const llama_memory_hybrid_context *>(params.mctx);
  378. this->mctx = mctx;
  379. bool res = true;
  380. res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens;
  381. //res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there
  382. res &= inp_attn->self_kq_mask->ne[0] == mctx->get_attn()->get_n_kv();
  383. res &= inp_attn->self_kq_mask->ne[1] == params.ubatch.n_tokens;
  384. res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs();
  385. res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs;
  386. res &= inp_rs->s_copy_extra->ne[0] == mctx->get_recr()->get_n_rs() - params.ubatch.n_seqs;
  387. res &= inp_rs->head == mctx->get_recr()->get_head();
  388. res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z();
  389. return res;
  390. }
  391. //
  392. // llm_graph_result
  393. //
  394. llm_graph_result::llm_graph_result(int64_t max_nodes) : max_nodes(max_nodes) {
  395. reset();
  396. const char * LLAMA_GRAPH_RESULT_DEBUG = getenv("LLAMA_GRAPH_RESULT_DEBUG");
  397. debug = LLAMA_GRAPH_RESULT_DEBUG ? atoi(LLAMA_GRAPH_RESULT_DEBUG) : 0;
  398. }
  399. int64_t llm_graph_result::get_max_nodes() const {
  400. return max_nodes;
  401. }
  402. void llm_graph_result::reset() {
  403. t_tokens = nullptr;
  404. t_logits = nullptr;
  405. t_embd = nullptr;
  406. t_embd_pooled = nullptr;
  407. params = {};
  408. inputs.clear();
  409. buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  410. ggml_init_params params = {
  411. /*.mem_size =*/ buf_compute_meta.size(),
  412. /*.mem_buffer =*/ buf_compute_meta.data(),
  413. /*.no_alloc =*/ true,
  414. };
  415. ctx_compute.reset(ggml_init(params));
  416. gf = ggml_new_graph_custom(ctx_compute.get(), max_nodes, false);
  417. }
  418. void llm_graph_result::set_inputs(const llama_ubatch * ubatch) {
  419. for (auto & input : inputs) {
  420. input->set_input(ubatch);
  421. }
  422. }
  423. bool llm_graph_result::can_reuse(const llm_graph_params & params) {
  424. if (!this->params.allow_reuse(params)) {
  425. if (debug > 1) {
  426. LLAMA_LOG_DEBUG("%s: cannot reuse graph due to incompatible graph parameters\n", __func__);
  427. }
  428. return false;
  429. }
  430. if (debug > 1) {
  431. LLAMA_LOG_DEBUG("%s: checking compatibility of %d inputs:\n", __func__, (int) inputs.size());
  432. }
  433. bool res = true;
  434. for (auto & input : inputs) {
  435. const bool cur = input->can_reuse(params);
  436. if (debug > 1) {
  437. LLAMA_LOG_DEBUG("%s: can_reuse = %d\n", "placeholder", cur);
  438. }
  439. res = res && cur;
  440. }
  441. if (debug > 0) {
  442. LLAMA_LOG_DEBUG("%s: can reuse graph = %d\n", __func__, res);
  443. }
  444. return res;
  445. }
  446. llm_graph_input_i * llm_graph_result::add_input(llm_graph_input_ptr input) {
  447. inputs.emplace_back(std::move(input));
  448. return inputs.back().get();
  449. }
  450. void llm_graph_result::set_params(const llm_graph_params & params) {
  451. this->params = params;
  452. }
  453. //
  454. // llm_graph_context
  455. //
  456. llm_graph_context::llm_graph_context(const llm_graph_params & params) :
  457. arch (params.arch),
  458. hparams (params.hparams),
  459. cparams (params.cparams),
  460. ubatch (params.ubatch),
  461. n_embd (hparams.n_embd),
  462. n_layer (hparams.n_layer),
  463. n_rot (hparams.n_rot),
  464. n_ctx (cparams.n_ctx),
  465. n_head (hparams.n_head()),
  466. n_head_kv (hparams.n_head_kv()),
  467. n_embd_head_k (hparams.n_embd_head_k),
  468. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  469. n_embd_head_v (hparams.n_embd_head_v),
  470. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  471. n_expert (hparams.n_expert),
  472. n_expert_used (cparams.warmup ? hparams.n_expert : hparams.n_expert_used),
  473. freq_base (cparams.rope_freq_base),
  474. freq_scale (cparams.rope_freq_scale),
  475. ext_factor (cparams.yarn_ext_factor),
  476. attn_factor (cparams.yarn_attn_factor),
  477. beta_fast (cparams.yarn_beta_fast),
  478. beta_slow (cparams.yarn_beta_slow),
  479. norm_eps (hparams.f_norm_eps),
  480. norm_rms_eps (hparams.f_norm_rms_eps),
  481. n_tokens (ubatch.n_tokens),
  482. n_outputs (params.n_outputs),
  483. n_ctx_orig (cparams.n_ctx_orig_yarn),
  484. pooling_type (cparams.pooling_type),
  485. rope_type (hparams.rope_type),
  486. sched (params.sched),
  487. backend_cpu (params.backend_cpu),
  488. cvec (params.cvec),
  489. loras (params.loras),
  490. mctx (params.mctx),
  491. cross (params.cross),
  492. cb_func (params.cb),
  493. res (params.res),
  494. ctx0 (res->get_ctx()),
  495. gf (res->get_gf()) {
  496. res->set_params(params);
  497. }
  498. void llm_graph_context::cb(ggml_tensor * cur, const char * name, int il) const {
  499. if (cb_func) {
  500. cb_func(ubatch, cur, name, il);
  501. }
  502. }
  503. ggml_tensor * llm_graph_context::build_cvec(
  504. ggml_tensor * cur,
  505. int il) const {
  506. return cvec->apply_to(ctx0, cur, il);
  507. }
  508. ggml_tensor * llm_graph_context::build_lora_mm(
  509. ggml_tensor * w,
  510. ggml_tensor * cur) const {
  511. ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  512. for (const auto & lora : *loras) {
  513. llama_adapter_lora_weight * lw = lora.first->get_weight(w);
  514. if (lw == nullptr) {
  515. continue;
  516. }
  517. const float adapter_scale = lora.second;
  518. const float scale = lw->get_scale(lora.first->alpha, adapter_scale);
  519. ggml_tensor * ab_cur = ggml_mul_mat(
  520. ctx0, lw->b,
  521. ggml_mul_mat(ctx0, lw->a, cur)
  522. );
  523. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  524. res = ggml_add(ctx0, res, ab_cur);
  525. }
  526. return res;
  527. }
  528. ggml_tensor * llm_graph_context::build_lora_mm_id(
  529. ggml_tensor * w, // ggml_tensor * as
  530. ggml_tensor * cur, // ggml_tensor * b
  531. ggml_tensor * ids) const {
  532. ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  533. for (const auto & lora : *loras) {
  534. llama_adapter_lora_weight * lw = lora.first->get_weight(w);
  535. if (lw == nullptr) {
  536. continue;
  537. }
  538. const float alpha = lora.first->alpha;
  539. const float rank = (float) lw->b->ne[0];
  540. const float scale = alpha ? lora.second * alpha / rank : lora.second;
  541. ggml_tensor * ab_cur = ggml_mul_mat_id(
  542. ctx0, lw->b,
  543. ggml_mul_mat_id(ctx0, lw->a, cur, ids),
  544. ids
  545. );
  546. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  547. res = ggml_add(ctx0, res, ab_cur);
  548. }
  549. return res;
  550. }
  551. ggml_tensor * llm_graph_context::build_norm(
  552. ggml_tensor * cur,
  553. ggml_tensor * mw,
  554. ggml_tensor * mb,
  555. llm_norm_type type,
  556. int il) const {
  557. switch (type) {
  558. case LLM_NORM: cur = ggml_norm (ctx0, cur, hparams.f_norm_eps); break;
  559. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx0, cur, hparams.f_norm_rms_eps); break;
  560. case LLM_NORM_GROUP:
  561. {
  562. cur = ggml_reshape_3d(ctx0, cur, cur->ne[0], 1, cur->ne[1]);
  563. cur = ggml_group_norm(ctx0, cur, hparams.n_norm_groups, hparams.f_norm_group_eps);
  564. cur = ggml_reshape_2d(ctx0, cur, cur->ne[0], cur->ne[2]);
  565. } break;
  566. }
  567. if (mw || mb) {
  568. cb(cur, "norm", il);
  569. }
  570. if (mw) {
  571. cur = ggml_mul(ctx0, cur, mw);
  572. if (mb) {
  573. cb(cur, "norm_w", il);
  574. }
  575. }
  576. if (mb) {
  577. cur = ggml_add(ctx0, cur, mb);
  578. }
  579. return cur;
  580. }
  581. ggml_tensor * llm_graph_context::build_ffn(
  582. ggml_tensor * cur,
  583. ggml_tensor * up,
  584. ggml_tensor * up_b,
  585. ggml_tensor * up_s,
  586. ggml_tensor * gate,
  587. ggml_tensor * gate_b,
  588. ggml_tensor * gate_s,
  589. ggml_tensor * down,
  590. ggml_tensor * down_b,
  591. ggml_tensor * down_s,
  592. ggml_tensor * act_scales,
  593. llm_ffn_op_type type_op,
  594. llm_ffn_gate_type type_gate,
  595. int il) const {
  596. ggml_tensor * tmp = up ? build_lora_mm(up, cur) : cur;
  597. cb(tmp, "ffn_up", il);
  598. if (up_b) {
  599. tmp = ggml_add(ctx0, tmp, up_b);
  600. cb(tmp, "ffn_up_b", il);
  601. }
  602. if (up_s) {
  603. tmp = ggml_mul(ctx0, tmp, up_s);
  604. cb(tmp, "ffn_up_s", il);
  605. }
  606. if (gate) {
  607. switch (type_gate) {
  608. case LLM_FFN_SEQ:
  609. {
  610. cur = build_lora_mm(gate, tmp);
  611. cb(cur, "ffn_gate", il);
  612. } break;
  613. case LLM_FFN_PAR:
  614. {
  615. cur = build_lora_mm(gate, cur);
  616. cb(cur, "ffn_gate", il);
  617. } break;
  618. }
  619. if (gate_b) {
  620. cur = ggml_add(ctx0, cur, gate_b);
  621. cb(cur, "ffn_gate_b", il);
  622. }
  623. if (gate_s) {
  624. cur = ggml_mul(ctx0, cur, gate_s);
  625. cb(cur, "ffn_gate_s", il);
  626. }
  627. } else {
  628. cur = tmp;
  629. }
  630. switch (type_op) {
  631. case LLM_FFN_SILU:
  632. if (gate && type_gate == LLM_FFN_PAR) {
  633. cur = ggml_swiglu_split(ctx0, cur, tmp);
  634. cb(cur, "ffn_swiglu", il);
  635. type_gate = LLM_FFN_SEQ;
  636. } else {
  637. cur = ggml_silu(ctx0, cur);
  638. cb(cur, "ffn_silu", il);
  639. } break;
  640. case LLM_FFN_GELU:
  641. if (gate && type_gate == LLM_FFN_PAR) {
  642. cur = ggml_geglu_split(ctx0, cur, tmp);
  643. cb(cur, "ffn_geglu", il);
  644. type_gate = LLM_FFN_SEQ;
  645. } else {
  646. cur = ggml_gelu(ctx0, cur);
  647. cb(cur, "ffn_gelu", il);
  648. if (act_scales != NULL) {
  649. cur = ggml_div(ctx0, cur, act_scales);
  650. cb(cur, "ffn_act", il);
  651. }
  652. } break;
  653. case LLM_FFN_RELU:
  654. if (gate && type_gate == LLM_FFN_PAR) {
  655. cur = ggml_reglu_split(ctx0, cur, tmp);
  656. cb(cur, "ffn_reglu", il);
  657. type_gate = LLM_FFN_SEQ;
  658. } else {
  659. cur = ggml_relu(ctx0, cur);
  660. cb(cur, "ffn_relu", il);
  661. } break;
  662. case LLM_FFN_RELU_SQR:
  663. {
  664. cur = ggml_relu(ctx0, cur);
  665. cb(cur, "ffn_relu", il);
  666. cur = ggml_sqr(ctx0, cur);
  667. cb(cur, "ffn_sqr(relu)", il);
  668. } break;
  669. case LLM_FFN_SWIGLU:
  670. {
  671. cur = ggml_swiglu(ctx0, cur);
  672. cb(cur, "ffn_swiglu", il);
  673. } break;
  674. case LLM_FFN_GEGLU:
  675. {
  676. cur = ggml_geglu(ctx0, cur);
  677. cb(cur, "ffn_geglu", il);
  678. } break;
  679. case LLM_FFN_REGLU:
  680. {
  681. cur = ggml_reglu(ctx0, cur);
  682. cb(cur, "ffn_reglu", il);
  683. } break;
  684. default:
  685. GGML_ABORT("fatal error");
  686. }
  687. if (gate && type_gate == LLM_FFN_PAR) {
  688. cur = ggml_mul(ctx0, cur, tmp);
  689. cb(cur, "ffn_gate_par", il);
  690. }
  691. if (down) {
  692. cur = build_lora_mm(down, cur);
  693. if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE) {
  694. // GLM4 and GLM4_MOE seem to have numerical issues with half-precision accumulators
  695. ggml_mul_mat_set_prec(cur, GGML_PREC_F32);
  696. }
  697. }
  698. if (down_b) {
  699. cb(cur, "ffn_down", il);
  700. }
  701. if (down_b) {
  702. cur = ggml_add(ctx0, cur, down_b);
  703. }
  704. if (down_s) {
  705. cur = ggml_mul(ctx0, cur, down_s);
  706. cb(cur, "ffn_down_s", il);
  707. }
  708. return cur;
  709. }
  710. ggml_tensor * llm_graph_context::build_moe_ffn(
  711. ggml_tensor * cur,
  712. ggml_tensor * gate_inp,
  713. ggml_tensor * up_exps,
  714. ggml_tensor * gate_exps,
  715. ggml_tensor * down_exps,
  716. ggml_tensor * exp_probs_b,
  717. int64_t n_expert,
  718. int64_t n_expert_used,
  719. llm_ffn_op_type type_op,
  720. bool norm_w,
  721. bool scale_w,
  722. float w_scale,
  723. llama_expert_gating_func_type gating_op,
  724. int il,
  725. ggml_tensor * probs_in) const {
  726. return build_moe_ffn(
  727. cur,
  728. gate_inp, /* gate_inp_b */ nullptr,
  729. up_exps, /* up_exps_b */ nullptr,
  730. gate_exps, /* gate_exps_b */ nullptr,
  731. down_exps, /* down_exps_b */ nullptr,
  732. exp_probs_b,
  733. n_expert,
  734. n_expert_used,
  735. type_op,
  736. norm_w,
  737. scale_w,
  738. w_scale,
  739. gating_op,
  740. il,
  741. probs_in
  742. );
  743. }
  744. ggml_tensor * llm_graph_context::build_moe_ffn(
  745. ggml_tensor * cur,
  746. ggml_tensor * gate_inp,
  747. ggml_tensor * gate_inp_b,
  748. ggml_tensor * up_exps,
  749. ggml_tensor * up_exps_b,
  750. ggml_tensor * gate_exps,
  751. ggml_tensor * gate_exps_b,
  752. ggml_tensor * down_exps,
  753. ggml_tensor * down_exps_b,
  754. ggml_tensor * exp_probs_b,
  755. int64_t n_expert,
  756. int64_t n_expert_used,
  757. llm_ffn_op_type type_op,
  758. bool norm_w,
  759. bool scale_w,
  760. float w_scale,
  761. llama_expert_gating_func_type gating_op,
  762. int il,
  763. ggml_tensor * probs_in) const {
  764. const int64_t n_embd = cur->ne[0];
  765. const int64_t n_tokens = cur->ne[1];
  766. const bool weight_before_ffn = arch == LLM_ARCH_LLAMA4; // for llama4, we apply the sigmoid-ed weights before the FFN
  767. ggml_tensor * logits = nullptr;
  768. if (probs_in == nullptr) {
  769. logits = build_lora_mm(gate_inp, cur); // [n_expert, n_tokens]
  770. cb(logits, "ffn_moe_logits", il);
  771. } else {
  772. logits = probs_in;
  773. }
  774. if (gate_inp_b) {
  775. logits = ggml_add(ctx0, logits, gate_inp_b);
  776. cb(logits, "ffn_moe_logits_biased", il);
  777. }
  778. ggml_tensor * probs = nullptr;
  779. switch (gating_op) {
  780. case LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX:
  781. {
  782. probs = ggml_soft_max(ctx0, logits); // [n_expert, n_tokens]
  783. } break;
  784. case LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID:
  785. {
  786. probs = ggml_sigmoid(ctx0, logits); // [n_expert, n_tokens]
  787. } break;
  788. case LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX_WEIGHT:
  789. {
  790. probs = logits; // [n_expert, n_tokens]
  791. } break;
  792. default:
  793. GGML_ABORT("fatal error");
  794. }
  795. cb(probs, "ffn_moe_probs", il);
  796. // add experts selection bias - introduced in DeepSeek V3
  797. // leave probs unbiased as it's later used to get expert weights
  798. ggml_tensor * selection_probs = probs;
  799. if (exp_probs_b != nullptr) {
  800. selection_probs = ggml_add(ctx0, probs, exp_probs_b);
  801. cb(selection_probs, "ffn_moe_probs_biased", il);
  802. }
  803. // llama4 doesn't have exp_probs_b, and sigmoid is only used after top_k
  804. // see: https://github.com/meta-llama/llama-models/blob/699a02993512fb36936b1b0741e13c06790bcf98/models/llama4/moe.py#L183-L198
  805. if (arch == LLM_ARCH_LLAMA4) {
  806. selection_probs = logits;
  807. }
  808. if (arch == LLM_ARCH_GROVEMOE) {
  809. selection_probs = ggml_sigmoid(ctx0, logits); // [n_expert, n_tokens]
  810. cb(selection_probs, "ffn_moe_probs_biased", il);
  811. }
  812. // select top n_group_used expert groups
  813. // https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/e815299b0bcbac849fa540c768ef21845365c9eb/modeling_deepseek.py#L440-L457
  814. if (hparams.n_expert_groups > 1 && n_tokens > 0) {
  815. const int64_t n_exp_per_group = n_expert / hparams.n_expert_groups;
  816. // organize experts into n_expert_groups
  817. ggml_tensor * selection_groups = ggml_reshape_3d(ctx0, selection_probs, n_exp_per_group, hparams.n_expert_groups, n_tokens); // [n_exp_per_group, n_expert_groups, n_tokens]
  818. ggml_tensor * group_scores = ggml_argsort_top_k(ctx0, selection_groups, 2); // [2, n_expert_groups, n_tokens]
  819. group_scores = ggml_get_rows(ctx0, ggml_reshape_4d(ctx0, selection_groups, 1, selection_groups->ne[0], selection_groups->ne[1], selection_groups->ne[2]), group_scores); // [1, 2, n_expert_groups, n_tokens]
  820. // get top n_group_used expert groups
  821. group_scores = ggml_sum_rows(ctx0, ggml_reshape_3d(ctx0, group_scores, group_scores->ne[1], group_scores->ne[2], group_scores->ne[3])); // [1, n_expert_groups, n_tokens]
  822. group_scores = ggml_reshape_2d(ctx0, group_scores, group_scores->ne[1], group_scores->ne[2]); // [n_expert_groups, n_tokens]
  823. ggml_tensor * expert_groups = ggml_argsort_top_k(ctx0, group_scores, hparams.n_group_used); // [n_group_used, n_tokens]
  824. cb(expert_groups, "ffn_moe_group_topk", il);
  825. // mask out the other groups
  826. selection_probs = ggml_get_rows(ctx0, selection_groups, expert_groups); // [n_exp_per_group, n_group_used, n_tokens]
  827. selection_probs = ggml_set_rows(ctx0, ggml_fill(ctx0, selection_groups, -INFINITY), selection_probs, expert_groups); // [n_exp_per_group, n_expert_groups, n_tokens]
  828. selection_probs = ggml_reshape_2d(ctx0, selection_probs, n_expert, n_tokens); // [n_expert, n_tokens]
  829. cb(selection_probs, "ffn_moe_probs_masked", il);
  830. }
  831. // select experts
  832. ggml_tensor * selected_experts = ggml_argsort_top_k(ctx0, selection_probs, n_expert_used); // [n_expert_used, n_tokens]
  833. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  834. cb(selected_experts, "ffn_moe_topk", il);
  835. if (arch == LLM_ARCH_GROVEMOE && n_expert != hparams.n_expert) {
  836. // TODO: Use scalar div instead when/if implemented
  837. ggml_tensor * f_sel = ggml_cast(ctx0, selected_experts, GGML_TYPE_F32);
  838. selected_experts = ggml_cast(ctx0, ggml_scale(ctx0, f_sel, 1.0f / float(hparams.n_group_experts)), GGML_TYPE_I32);
  839. probs = ggml_reshape_3d(ctx0, probs, 1, hparams.n_expert, n_tokens);
  840. } else {
  841. probs = ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens);
  842. }
  843. ggml_tensor * weights = ggml_get_rows(ctx0, probs, selected_experts); // [1, n_expert_used, n_tokens]
  844. cb(weights, "ffn_moe_weights", il);
  845. if (gating_op == LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX_WEIGHT) {
  846. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens);
  847. weights = ggml_soft_max(ctx0, weights); // [n_expert_used, n_tokens]
  848. weights = ggml_reshape_3d(ctx0, weights, 1, n_expert_used, n_tokens);
  849. cb(weights, "ffn_moe_weights_softmax", il);
  850. }
  851. if (norm_w) {
  852. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens);
  853. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights); // [1, n_tokens]
  854. cb(weights_sum, "ffn_moe_weights_sum", il);
  855. // Avoid division by zero, clamp to smallest number representable by F16
  856. weights_sum = ggml_clamp(ctx0, weights_sum, 6.103515625e-5, INFINITY);
  857. cb(weights_sum, "ffn_moe_weights_sum_clamped", il);
  858. weights = ggml_div(ctx0, weights, weights_sum); // [n_expert_used, n_tokens]
  859. cb(weights, "ffn_moe_weights_norm", il);
  860. weights = ggml_reshape_3d(ctx0, weights, 1, n_expert_used, n_tokens);
  861. }
  862. if (scale_w) {
  863. weights = ggml_scale(ctx0, weights, w_scale);
  864. cb(weights, "ffn_moe_weights_scaled", il);
  865. }
  866. //call early so that topk-moe can be used
  867. ggml_build_forward_expand(gf, weights);
  868. cur = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens);
  869. if (weight_before_ffn) {
  870. // repeat cur to [n_embd, n_expert_used, n_tokens]
  871. ggml_tensor * repeated = ggml_repeat_4d(ctx0, cur, n_embd, n_expert_used, n_tokens, 1);
  872. cur = ggml_mul(ctx0, repeated, weights);
  873. cb(cur, "ffn_moe_weighted", il);
  874. }
  875. ggml_tensor * up = build_lora_mm_id(up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  876. cb(up, "ffn_moe_up", il);
  877. if (up_exps_b) {
  878. up = ggml_add_id(ctx0, up, up_exps_b, selected_experts);
  879. cb(up, "ffn_moe_up_biased", il);
  880. }
  881. ggml_tensor * experts = nullptr;
  882. if (gate_exps) {
  883. cur = build_lora_mm_id(gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  884. cb(cur, "ffn_moe_gate", il);
  885. } else {
  886. cur = up;
  887. }
  888. if (gate_exps_b) {
  889. cur = ggml_add_id(ctx0, cur, gate_exps_b, selected_experts);
  890. cb(cur, "ffn_moe_gate_biased", il);
  891. }
  892. switch (type_op) {
  893. case LLM_FFN_SILU:
  894. if (gate_exps) {
  895. cur = ggml_swiglu_split(ctx0, cur, up);
  896. cb(cur, "ffn_moe_swiglu", il);
  897. } else {
  898. cur = ggml_silu(ctx0, cur);
  899. cb(cur, "ffn_moe_silu", il);
  900. } break;
  901. case LLM_FFN_GELU:
  902. if (gate_exps) {
  903. cur = ggml_geglu_split(ctx0, cur, up);
  904. cb(cur, "ffn_moe_geglu", il);
  905. } else {
  906. cur = ggml_gelu(ctx0, cur);
  907. cb(cur, "ffn_moe_gelu", il);
  908. } break;
  909. case LLM_FFN_SWIGLU_OAI_MOE:
  910. {
  911. // TODO: move to hparams?
  912. constexpr float alpha = 1.702f;
  913. constexpr float limit = 7.0f;
  914. cur = ggml_swiglu_oai(ctx0, cur, up, alpha, limit);
  915. cb(cur, "ffn_moe_swiglu_oai", il);
  916. } break;
  917. case LLM_FFN_RELU:
  918. if (gate_exps) {
  919. cur = ggml_reglu_split(ctx0, cur, up);
  920. cb(cur, "ffn_moe_reglu", il);
  921. } else {
  922. cur = ggml_relu(ctx0, cur);
  923. cb(cur, "ffn_moe_relu", il);
  924. } break;
  925. case LLM_FFN_RELU_SQR:
  926. if (gate_exps) {
  927. // TODO: add support for gated squared relu
  928. GGML_ABORT("fatal error: gated squared relu not implemented");
  929. } else {
  930. cur = ggml_relu(ctx0, cur);
  931. cur = ggml_sqr(ctx0, cur);
  932. cb(cur, "ffn_moe_relu_sqr", il);
  933. } break;
  934. default:
  935. GGML_ABORT("fatal error");
  936. }
  937. experts = build_lora_mm_id(down_exps, cur, selected_experts); // [n_embd, n_expert_used, n_tokens]
  938. cb(experts, "ffn_moe_down", il);
  939. if (down_exps_b) {
  940. experts = ggml_add_id(ctx0, experts, down_exps_b, selected_experts);
  941. cb(experts, "ffn_moe_down_biased", il);
  942. }
  943. if (!weight_before_ffn) {
  944. experts = ggml_mul(ctx0, experts, weights);
  945. cb(cur, "ffn_moe_weighted", il);
  946. }
  947. ggml_tensor * cur_experts[LLAMA_MAX_EXPERTS] = { nullptr };
  948. assert(n_expert_used > 0);
  949. // order the views before the adds
  950. for (uint32_t i = 0; i < hparams.n_expert_used; ++i) {
  951. cur_experts[i] = ggml_view_2d(ctx0, experts, n_embd, n_tokens, experts->nb[2], i*experts->nb[1]);
  952. ggml_build_forward_expand(gf, cur_experts[i]);
  953. }
  954. // aggregate experts
  955. // note: here we explicitly use hparams.n_expert_used instead of n_expert_used
  956. // to avoid potentially a large number of add nodes during warmup
  957. // ref: https://github.com/ggml-org/llama.cpp/pull/14753
  958. ggml_tensor * moe_out = cur_experts[0];
  959. for (uint32_t i = 1; i < hparams.n_expert_used; ++i) {
  960. moe_out = ggml_add(ctx0, moe_out, cur_experts[i]);
  961. }
  962. if (hparams.n_expert_used == 1) {
  963. // avoid returning a non-contiguous tensor
  964. moe_out = ggml_cont(ctx0, moe_out);
  965. }
  966. cb(moe_out, "ffn_moe_out", il);
  967. return moe_out;
  968. }
  969. // input embeddings with optional lora
  970. ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd) const {
  971. const int64_t n_embd = hparams.n_embd_inp();
  972. auto inp = std::make_unique<llm_graph_input_embd>();
  973. ggml_tensor * cur = nullptr;
  974. if (ubatch.token) {
  975. inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_tokens);
  976. //cb(inp->tokens, "inp_tokens", -1);
  977. ggml_set_input(inp->tokens);
  978. res->t_tokens = inp->tokens;
  979. cur = ggml_get_rows(ctx0, tok_embd, inp->tokens);
  980. // apply lora for embedding tokens if needed
  981. for (const auto & lora : *loras) {
  982. llama_adapter_lora_weight * lw = lora.first->get_weight(tok_embd);
  983. if (lw == nullptr) {
  984. continue;
  985. }
  986. const float adapter_scale = lora.second;
  987. const float scale = lw->get_scale(lora.first->alpha, adapter_scale);
  988. ggml_tensor * inpL_delta = ggml_scale(ctx0, ggml_mul_mat(
  989. ctx0, lw->b, // non-transposed lora_b
  990. ggml_get_rows(ctx0, lw->a, inp->tokens)
  991. ), scale);
  992. cur = ggml_add(ctx0, cur, inpL_delta);
  993. }
  994. } else {
  995. inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, ubatch.n_tokens);
  996. ggml_set_input(inp->embd);
  997. cur = inp->embd;
  998. }
  999. // For Granite architecture
  1000. if (hparams.f_embedding_scale != 0.0f) {
  1001. cur = ggml_scale(ctx0, cur, hparams.f_embedding_scale);
  1002. }
  1003. cb(cur, "inp_embd", -1);
  1004. res->add_input(std::move(inp));
  1005. return cur;
  1006. }
  1007. ggml_tensor * llm_graph_context::build_inp_pos() const {
  1008. auto inp = std::make_unique<llm_graph_input_pos>(hparams.n_pos_per_embd());
  1009. auto & cur = inp->pos;
  1010. cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, (int64_t)n_tokens*hparams.n_pos_per_embd());
  1011. ggml_set_input(cur);
  1012. res->add_input(std::move(inp));
  1013. return cur;
  1014. }
  1015. ggml_tensor * llm_graph_context::build_inp_attn_scale() const {
  1016. auto inp = std::make_unique<llm_graph_input_attn_temp>(hparams.n_attn_temp_floor_scale, hparams.f_attn_temp_scale, hparams.f_attn_temp_offset);
  1017. auto & cur = inp->attn_scale;
  1018. // this need to be 1x1xN for broadcasting
  1019. cur = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 1, 1, n_tokens);
  1020. ggml_set_input(cur);
  1021. res->add_input(std::move(inp));
  1022. return cur;
  1023. }
  1024. ggml_tensor * llm_graph_context::build_inp_out_ids() const {
  1025. // note: when all tokens are output, we could skip this optimization to spare the ggml_get_rows() calls,
  1026. // but this would make the graph topology depend on the number of output tokens, which can interere with
  1027. // features that require constant topology such as pipline parallelism
  1028. // ref: https://github.com/ggml-org/llama.cpp/pull/14275#issuecomment-2987424471
  1029. //if (n_outputs < n_tokens) {
  1030. // return nullptr;
  1031. //}
  1032. auto inp = std::make_unique<llm_graph_input_out_ids>(hparams, cparams, n_outputs);
  1033. auto & cur = inp->out_ids;
  1034. cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  1035. ggml_set_input(cur);
  1036. res->add_input(std::move(inp));
  1037. return cur;
  1038. }
  1039. ggml_tensor * llm_graph_context::build_inp_mean() const {
  1040. auto inp = std::make_unique<llm_graph_input_mean>(cparams);
  1041. auto & cur = inp->mean;
  1042. cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, ubatch.n_seqs_unq);
  1043. ggml_set_input(cur);
  1044. res->add_input(std::move(inp));
  1045. return cur;
  1046. }
  1047. ggml_tensor * llm_graph_context::build_inp_cls() const {
  1048. auto inp = std::make_unique<llm_graph_input_cls>(cparams, arch);
  1049. auto & cur = inp->cls;
  1050. cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_seqs_unq);
  1051. ggml_set_input(cur);
  1052. res->add_input(std::move(inp));
  1053. return cur;
  1054. }
  1055. ggml_tensor * llm_graph_context::build_inp_cross_embd() const {
  1056. auto inp = std::make_unique<llm_graph_input_cross_embd>(cross);
  1057. auto & cur = inp->cross_embd;
  1058. // if we have the output embeddings from the encoder, use them directly
  1059. // TODO: needs more work to be correct, for now just use the tensor shape
  1060. //if (cross->t_embd) {
  1061. // cur = ggml_view_tensor(ctx0, cross->t_embd);
  1062. // return cur;
  1063. //}
  1064. const auto n_embd = !cross->v_embd.empty() ? cross->n_embd : hparams.n_embd_inp();
  1065. const auto n_enc = !cross->v_embd.empty() ? cross->n_enc : hparams.n_ctx_train;
  1066. cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_enc);
  1067. ggml_set_input(cur);
  1068. res->add_input(std::move(inp));
  1069. return cur;
  1070. }
  1071. ggml_tensor * llm_graph_context::build_inp_pos_bucket_enc() const {
  1072. auto inp = std::make_unique<llm_graph_input_pos_bucket>(hparams);
  1073. auto & cur = inp->pos_bucket;
  1074. cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  1075. ggml_set_input(cur);
  1076. res->add_input(std::move(inp));
  1077. return cur;
  1078. }
  1079. ggml_tensor * llm_graph_context::build_inp_pos_bucket_dec() const {
  1080. const auto * mctx_cur = static_cast<const llama_kv_cache_context *>(mctx);
  1081. auto inp = std::make_unique<llm_graph_input_pos_bucket_kv>(hparams, mctx_cur);
  1082. const auto n_kv = mctx_cur->get_n_kv();
  1083. auto & cur = inp->pos_bucket;
  1084. cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  1085. ggml_set_input(cur);
  1086. res->add_input(std::move(inp));
  1087. return cur;
  1088. }
  1089. ggml_tensor * llm_graph_context::build_pos_bias(ggml_tensor * pos_bucket, ggml_tensor * attn_rel_b) const {
  1090. ggml_tensor * pos_bucket_1d = ggml_reshape_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1]);
  1091. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  1092. ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  1093. pos_bias = ggml_reshape_3d(ctx0, pos_bias, pos_bias->ne[0], pos_bucket->ne[0], pos_bucket->ne[1]);
  1094. pos_bias = ggml_permute (ctx0, pos_bias, 2, 0, 1, 3);
  1095. pos_bias = ggml_cont (ctx0, pos_bias);
  1096. cb(pos_bias, "pos_bias", -1);
  1097. return pos_bias;
  1098. }
  1099. ggml_tensor * llm_graph_context::build_attn_mha(
  1100. ggml_tensor * q,
  1101. ggml_tensor * k,
  1102. ggml_tensor * v,
  1103. ggml_tensor * kq_b,
  1104. ggml_tensor * kq_mask,
  1105. ggml_tensor * sinks,
  1106. ggml_tensor * v_mla,
  1107. float kq_scale,
  1108. int il) const {
  1109. const bool v_trans = v->nb[1] > v->nb[2];
  1110. // split the batch into streams if needed
  1111. const auto n_stream = k->ne[3];
  1112. q = ggml_view_4d(ctx0, q, q->ne[0], q->ne[1], q->ne[2]/n_stream, n_stream, q->nb[1], q->nb[2], q->nb[3]/n_stream, 0);
  1113. q = ggml_permute(ctx0, q, 0, 2, 1, 3);
  1114. k = ggml_permute(ctx0, k, 0, 2, 1, 3);
  1115. v = ggml_permute(ctx0, v, 0, 2, 1, 3);
  1116. ggml_tensor * cur;
  1117. if (cparams.flash_attn && kq_b == nullptr) {
  1118. GGML_ASSERT(kq_b == nullptr && "Flash attention does not support KQ bias yet");
  1119. if (v_trans) {
  1120. v = ggml_transpose(ctx0, v);
  1121. }
  1122. // this can happen when KV cache is not used (e.g. an embedding model with non-causal attn)
  1123. if (k->type == GGML_TYPE_F32) {
  1124. k = ggml_cast(ctx0, k, GGML_TYPE_F16);
  1125. }
  1126. if (v->type == GGML_TYPE_F32) {
  1127. v = ggml_cast(ctx0, v, GGML_TYPE_F16);
  1128. }
  1129. cur = ggml_flash_attn_ext(ctx0, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias,
  1130. hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f);
  1131. cb(cur, LLAMA_TENSOR_NAME_FATTN, il);
  1132. ggml_flash_attn_ext_add_sinks(cur, sinks);
  1133. ggml_flash_attn_ext_set_prec (cur, GGML_PREC_F32);
  1134. if (v_mla) {
  1135. #if 0
  1136. // v_mla can be applied as a matrix-vector multiplication with broadcasting across dimension 3 == n_tokens.
  1137. // However, the code is optimized for dimensions 0 and 1 being large, so this is ineffient.
  1138. cur = ggml_reshape_4d(ctx0, cur, v_mla->ne[0], 1, n_head, n_tokens);
  1139. cur = ggml_mul_mat(ctx0, v_mla, cur);
  1140. #else
  1141. // It's preferable to do the calculation as a matrix-matrix multiplication with n_tokens in dimension 1.
  1142. // The permutations are noops and only change how the tensor data is interpreted.
  1143. cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
  1144. cur = ggml_mul_mat(ctx0, v_mla, cur);
  1145. cb(cur, "fattn_mla", il);
  1146. cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
  1147. cur = ggml_cont(ctx0, cur); // Needed because ggml_reshape_2d expects contiguous inputs.
  1148. #endif
  1149. }
  1150. cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]);
  1151. } else {
  1152. ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  1153. cb(kq, "kq", il);
  1154. // note: this op tends to require high floating point range
  1155. // while for some models F16 is enough, for others it is not, so we default to F32 here
  1156. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  1157. if (arch == LLM_ARCH_GROK) {
  1158. // need to do the following:
  1159. // multiply by attn_output_multiplier
  1160. // and then :
  1161. // kq = 30 * tanh(kq / 30)
  1162. // before the softmax below
  1163. kq = ggml_tanh(ctx0, ggml_scale(ctx0, kq, hparams.f_attn_out_scale / hparams.f_attn_logit_softcapping));
  1164. cb(kq, "kq_tanh", il);
  1165. kq = ggml_scale(ctx0, kq, hparams.f_attn_logit_softcapping);
  1166. cb(kq, "kq_scaled", il);
  1167. }
  1168. if (hparams.attn_soft_cap) {
  1169. kq = ggml_scale(ctx0, kq, 1.0f / hparams.f_attn_logit_softcapping);
  1170. cb(kq, "kq_scaled_1", il);
  1171. kq = ggml_tanh (ctx0, kq);
  1172. cb(kq, "kq_tanh", il);
  1173. kq = ggml_scale(ctx0, kq, hparams.f_attn_logit_softcapping);
  1174. cb(kq, "kq_scaled_2", il);
  1175. }
  1176. if (kq_b) {
  1177. kq = ggml_add(ctx0, kq, kq_b);
  1178. cb(kq, "kq_plus_kq_b", il);
  1179. }
  1180. kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  1181. ggml_soft_max_add_sinks(kq, sinks);
  1182. cb(kq, "kq_soft_max", il);
  1183. if (!v_trans) {
  1184. // note: avoid this branch
  1185. v = ggml_cont(ctx0, ggml_transpose(ctx0, v));
  1186. cb(v, "v_cont", il);
  1187. }
  1188. ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  1189. cb(kqv, "kqv", il);
  1190. // for MLA with the absorption optimization, we need to "decompress" from MQA back to MHA
  1191. if (v_mla) {
  1192. kqv = ggml_mul_mat(ctx0, v_mla, kqv);
  1193. cb(kqv, "kqv_mla", il);
  1194. }
  1195. cur = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  1196. // recombine streams
  1197. cur = ggml_cont_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]);
  1198. if (!cparams.offload_kqv) {
  1199. // all nodes between the KV store and the attention output are run on the CPU
  1200. ggml_backend_sched_set_tensor_backend(sched, cur, backend_cpu);
  1201. }
  1202. }
  1203. ggml_build_forward_expand(gf, cur);
  1204. return cur;
  1205. }
  1206. llm_graph_input_attn_no_cache * llm_graph_context::build_attn_inp_no_cache() const {
  1207. auto inp = std::make_unique<llm_graph_input_attn_no_cache>(hparams, cparams);
  1208. // note: there is no KV cache, so the number of KV values is equal to the number of tokens in the batch
  1209. inp->self_kq_mask = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens, 1, 1);
  1210. ggml_set_input(inp->self_kq_mask);
  1211. inp->self_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask, GGML_TYPE_F16) : inp->self_kq_mask;
  1212. if (hparams.swa_type != LLAMA_SWA_TYPE_NONE) {
  1213. inp->self_kq_mask_swa = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens, 1, 1);
  1214. ggml_set_input(inp->self_kq_mask_swa);
  1215. inp->self_kq_mask_swa_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask_swa, GGML_TYPE_F16) : inp->self_kq_mask_swa;
  1216. } else {
  1217. inp->self_kq_mask_swa = nullptr;
  1218. inp->self_kq_mask_swa_cnv = nullptr;
  1219. }
  1220. return (llm_graph_input_attn_no_cache *) res->add_input(std::move(inp));
  1221. }
  1222. ggml_tensor * llm_graph_context::build_attn(
  1223. llm_graph_input_attn_no_cache * inp,
  1224. ggml_tensor * wo,
  1225. ggml_tensor * wo_b,
  1226. ggml_tensor * q_cur,
  1227. ggml_tensor * k_cur,
  1228. ggml_tensor * v_cur,
  1229. ggml_tensor * kq_b,
  1230. ggml_tensor * sinks,
  1231. ggml_tensor * v_mla,
  1232. float kq_scale,
  1233. int il) const {
  1234. GGML_UNUSED(n_tokens);
  1235. // these nodes are added to the graph together so that they are not reordered
  1236. // by doing so, the number of splits in the graph is reduced
  1237. ggml_build_forward_expand(gf, q_cur);
  1238. ggml_build_forward_expand(gf, k_cur);
  1239. ggml_build_forward_expand(gf, v_cur);
  1240. const bool is_swa = hparams.is_swa(il);
  1241. const auto & kq_mask = is_swa ? inp->get_kq_mask_swa() : inp->get_kq_mask();
  1242. // [TAG_NO_CACHE_PAD]
  1243. // TODO: if ubatch.equal_seqs() == true, we can split the three tensors below into ubatch.n_seqs_unq streams
  1244. // but it might not be worth it: https://github.com/ggml-org/llama.cpp/pull/15636
  1245. //assert(!ubatch.equal_seqs() || (k_cur->ne[3] == 1 && k_cur->ne[3] == ubatch.n_seqs_unq));
  1246. ggml_tensor * q = q_cur;
  1247. ggml_tensor * k = k_cur;
  1248. ggml_tensor * v = v_cur;
  1249. ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, kq_scale, il);
  1250. cb(cur, "kqv_out", il);
  1251. if (wo) {
  1252. cur = build_lora_mm(wo, cur);
  1253. }
  1254. if (wo_b) {
  1255. //cb(cur, "kqv_wo", il);
  1256. }
  1257. if (wo_b) {
  1258. cur = ggml_add(ctx0, cur, wo_b);
  1259. }
  1260. return cur;
  1261. }
  1262. static std::unique_ptr<llm_graph_input_attn_kv> build_attn_inp_kv_impl(
  1263. ggml_context * ctx0,
  1264. const llama_ubatch & ubatch,
  1265. const llama_hparams & hparams,
  1266. const llama_cparams & cparams,
  1267. const llama_kv_cache_context * mctx_cur) {
  1268. auto inp = std::make_unique<llm_graph_input_attn_kv>(hparams, cparams, mctx_cur);
  1269. {
  1270. GGML_ASSERT(hparams.swa_type == LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache_iswa for SWA");
  1271. const auto n_kv = mctx_cur->get_n_kv();
  1272. const auto n_tokens = ubatch.n_tokens;
  1273. const auto n_stream = cparams.kv_unified ? 1 : ubatch.n_seqs_unq;
  1274. inp->self_k_idxs = mctx_cur->build_input_k_idxs(ctx0, ubatch);
  1275. inp->self_v_idxs = mctx_cur->build_input_v_idxs(ctx0, ubatch);
  1276. inp->self_kq_mask = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_kv, n_tokens/n_stream, 1, n_stream);
  1277. ggml_set_input(inp->self_kq_mask);
  1278. inp->self_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask, GGML_TYPE_F16) : inp->self_kq_mask;
  1279. }
  1280. return inp;
  1281. }
  1282. llm_graph_input_attn_kv * llm_graph_context::build_attn_inp_kv() const {
  1283. const auto * mctx_cur = static_cast<const llama_kv_cache_context *>(mctx);
  1284. auto inp = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur);
  1285. return (llm_graph_input_attn_kv *) res->add_input(std::move(inp));
  1286. }
  1287. ggml_tensor * llm_graph_context::build_attn(
  1288. llm_graph_input_attn_kv * inp,
  1289. ggml_tensor * wo,
  1290. ggml_tensor * wo_b,
  1291. ggml_tensor * q_cur,
  1292. ggml_tensor * k_cur,
  1293. ggml_tensor * v_cur,
  1294. ggml_tensor * kq_b,
  1295. ggml_tensor * sinks,
  1296. ggml_tensor * v_mla,
  1297. float kq_scale,
  1298. int il) const {
  1299. // these nodes are added to the graph together so that they are not reordered
  1300. // by doing so, the number of splits in the graph is reduced
  1301. // expand k later to enable rope fusion which directly writes into k-v cache
  1302. ggml_build_forward_expand(gf, q_cur);
  1303. ggml_build_forward_expand(gf, v_cur);
  1304. ggml_build_forward_expand(gf, k_cur);
  1305. const auto * mctx_cur = inp->mctx;
  1306. // store to KV cache
  1307. {
  1308. const auto & k_idxs = inp->get_k_idxs();
  1309. const auto & v_idxs = inp->get_v_idxs();
  1310. ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il));
  1311. ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il));
  1312. }
  1313. const auto & kq_mask = inp->get_kq_mask();
  1314. ggml_tensor * q = q_cur;
  1315. ggml_tensor * k = mctx_cur->get_k(ctx0, il);
  1316. ggml_tensor * v = mctx_cur->get_v(ctx0, il);
  1317. ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, kq_scale, il);
  1318. cb(cur, "kqv_out", il);
  1319. if (wo) {
  1320. cur = build_lora_mm(wo, cur);
  1321. if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE) {
  1322. // GLM4 and GLM4_MOE seem to have numerical issues with half-precision accumulators
  1323. ggml_mul_mat_set_prec(cur, GGML_PREC_F32);
  1324. }
  1325. }
  1326. if (wo_b) {
  1327. cur = ggml_add(ctx0, cur, wo_b);
  1328. }
  1329. return cur;
  1330. }
  1331. ggml_tensor * llm_graph_context::build_attn(
  1332. llm_graph_input_attn_kv_iswa * inp,
  1333. ggml_tensor * wo,
  1334. ggml_tensor * wo_b,
  1335. ggml_tensor * q_cur,
  1336. ggml_tensor * k_cur,
  1337. ggml_tensor * v_cur,
  1338. ggml_tensor * kq_b,
  1339. ggml_tensor * sinks,
  1340. ggml_tensor * v_mla,
  1341. float kq_scale,
  1342. int il) const {
  1343. // these nodes are added to the graph together so that they are not reordered
  1344. // by doing so, the number of splits in the graph is reduced
  1345. ggml_build_forward_expand(gf, q_cur);
  1346. if (k_cur) {
  1347. ggml_build_forward_expand(gf, k_cur);
  1348. }
  1349. if (v_cur) {
  1350. ggml_build_forward_expand(gf, v_cur);
  1351. }
  1352. const auto * mctx_iswa = inp->mctx;
  1353. const bool is_swa = hparams.is_swa(il);
  1354. const auto * mctx_cur = is_swa ? mctx_iswa->get_swa() : mctx_iswa->get_base();
  1355. // optionally store to KV cache
  1356. if (k_cur) {
  1357. const auto & k_idxs = is_swa ? inp->get_k_idxs_swa() : inp->get_k_idxs();
  1358. ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il));
  1359. }
  1360. if (v_cur) {
  1361. const auto & v_idxs = is_swa ? inp->get_v_idxs_swa() : inp->get_v_idxs();
  1362. ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il));
  1363. }
  1364. const auto & kq_mask = is_swa ? inp->get_kq_mask_swa() : inp->get_kq_mask();
  1365. ggml_tensor * q = q_cur;
  1366. ggml_tensor * k = mctx_cur->get_k(ctx0, il);
  1367. ggml_tensor * v = mctx_cur->get_v(ctx0, il);
  1368. ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, kq_scale, il);
  1369. cb(cur, "kqv_out", il);
  1370. if (wo) {
  1371. cur = build_lora_mm(wo, cur);
  1372. }
  1373. if (wo_b) {
  1374. //cb(cur, "kqv_wo", il);
  1375. }
  1376. if (wo_b) {
  1377. cur = ggml_add(ctx0, cur, wo_b);
  1378. }
  1379. return cur;
  1380. }
  1381. llm_graph_input_attn_cross * llm_graph_context::build_attn_inp_cross() const {
  1382. auto inp = std::make_unique<llm_graph_input_attn_cross>(cross);
  1383. const int32_t n_enc = !cross->v_embd.empty() ? cross->n_enc : hparams.n_ctx_train;
  1384. inp->cross_kq_mask = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_enc, n_tokens, 1, 1);
  1385. ggml_set_input(inp->cross_kq_mask);
  1386. inp->cross_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->cross_kq_mask, GGML_TYPE_F16) : inp->cross_kq_mask;
  1387. return (llm_graph_input_attn_cross *) res->add_input(std::move(inp));
  1388. }
  1389. ggml_tensor * llm_graph_context::build_attn(
  1390. llm_graph_input_attn_cross * inp,
  1391. ggml_tensor * wo,
  1392. ggml_tensor * wo_b,
  1393. ggml_tensor * q_cur,
  1394. ggml_tensor * k_cur,
  1395. ggml_tensor * v_cur,
  1396. ggml_tensor * kq_b,
  1397. ggml_tensor * sinks,
  1398. ggml_tensor * v_mla,
  1399. float kq_scale,
  1400. int il) const {
  1401. // these nodes are added to the graph together so that they are not reordered
  1402. // by doing so, the number of splits in the graph is reduced
  1403. ggml_build_forward_expand(gf, q_cur);
  1404. ggml_build_forward_expand(gf, k_cur);
  1405. ggml_build_forward_expand(gf, v_cur);
  1406. const auto & kq_mask = inp->get_kq_mask_cross();
  1407. ggml_tensor * q = q_cur;
  1408. ggml_tensor * k = k_cur;
  1409. ggml_tensor * v = v_cur;
  1410. ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, kq_scale, il);
  1411. cb(cur, "kqv_out", il);
  1412. if (wo) {
  1413. cur = build_lora_mm(wo, cur);
  1414. }
  1415. if (wo_b) {
  1416. //cb(cur, "kqv_wo", il);
  1417. }
  1418. if (wo_b) {
  1419. cur = ggml_add(ctx0, cur, wo_b);
  1420. }
  1421. return cur;
  1422. }
  1423. // TODO: maybe separate the inner implementation into a separate function
  1424. // like with the non-sliding window equivalent
  1425. // once sliding-window hybrid caches are a thing.
  1426. llm_graph_input_attn_kv_iswa * llm_graph_context::build_attn_inp_kv_iswa() const {
  1427. const auto * mctx_cur = static_cast<const llama_kv_cache_iswa_context *>(mctx);
  1428. auto inp = std::make_unique<llm_graph_input_attn_kv_iswa>(hparams, cparams, mctx_cur);
  1429. const auto n_stream = cparams.kv_unified ? 1 : ubatch.n_seqs_unq;
  1430. {
  1431. const auto n_kv = mctx_cur->get_base()->get_n_kv();
  1432. inp->self_k_idxs = mctx_cur->get_base()->build_input_k_idxs(ctx0, ubatch);
  1433. inp->self_v_idxs = mctx_cur->get_base()->build_input_v_idxs(ctx0, ubatch);
  1434. inp->self_kq_mask = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_kv, n_tokens/n_stream, 1, n_stream);
  1435. ggml_set_input(inp->self_kq_mask);
  1436. inp->self_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask, GGML_TYPE_F16) : inp->self_kq_mask;
  1437. }
  1438. {
  1439. GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache for non-SWA");
  1440. const auto n_kv = mctx_cur->get_swa()->get_n_kv();
  1441. inp->self_k_idxs_swa = mctx_cur->get_swa()->build_input_k_idxs(ctx0, ubatch);
  1442. inp->self_v_idxs_swa = mctx_cur->get_swa()->build_input_v_idxs(ctx0, ubatch);
  1443. inp->self_kq_mask_swa = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_kv, n_tokens/n_stream, 1, n_stream);
  1444. ggml_set_input(inp->self_kq_mask_swa);
  1445. inp->self_kq_mask_swa_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask_swa, GGML_TYPE_F16) : inp->self_kq_mask_swa;
  1446. }
  1447. return (llm_graph_input_attn_kv_iswa *) res->add_input(std::move(inp));
  1448. }
  1449. ggml_tensor * llm_graph_context::build_rs(
  1450. ggml_tensor * s,
  1451. ggml_tensor * state_copy_main,
  1452. ggml_tensor * state_copy_extra,
  1453. int32_t state_size,
  1454. int32_t n_seqs,
  1455. uint32_t n_rs,
  1456. uint32_t rs_head,
  1457. uint32_t rs_size,
  1458. int32_t rs_zero,
  1459. const llm_graph_get_rows_fn & get_state_rows) const {
  1460. ggml_tensor * states = ggml_reshape_2d(ctx0, s, state_size, rs_size);
  1461. // Clear a single state which will then be copied to the other cleared states.
  1462. // Note that this is a no-op when the view is zero-sized.
  1463. ggml_tensor * state_zero = ggml_view_1d(ctx0, states, state_size*(rs_zero >= 0), rs_zero*states->nb[1]*(rs_zero >= 0));
  1464. ggml_build_forward_expand(gf, ggml_scale_inplace(ctx0, state_zero, 0));
  1465. // copy states
  1466. // NOTE: assuming the copy destinations are ALL contained between rs_head and rs_head + n_rs
  1467. // {state_size, rs_size} -> {state_size, n_seqs}
  1468. ggml_tensor * output_states = get_state_rows(ctx0, states, state_copy_main);
  1469. ggml_build_forward_expand(gf, output_states);
  1470. // copy extra states which won't be changed further (between n_seqs and n_rs)
  1471. ggml_tensor * states_extra = ggml_get_rows(ctx0, states, state_copy_extra);
  1472. ggml_build_forward_expand(gf,
  1473. ggml_cpy(ctx0,
  1474. states_extra,
  1475. ggml_view_1d(ctx0, s, state_size*(n_rs - n_seqs), (rs_head + n_seqs)*state_size*ggml_element_size(s))));
  1476. return output_states;
  1477. }
  1478. static std::unique_ptr<llm_graph_input_rs> build_rs_inp_impl(
  1479. ggml_context * ctx0,
  1480. const llama_ubatch & ubatch,
  1481. const llama_memory_recurrent_context * mctx_cur) {
  1482. auto inp = std::make_unique<llm_graph_input_rs>(mctx_cur);
  1483. const int64_t n_rs = mctx_cur->get_n_rs();
  1484. const int64_t n_seqs = ubatch.n_seqs;
  1485. inp->s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_rs);
  1486. ggml_set_input(inp->s_copy);
  1487. inp->s_copy_main = ggml_view_1d(ctx0, inp->s_copy, n_seqs, 0);
  1488. inp->s_copy_extra = ggml_view_1d(ctx0, inp->s_copy, n_rs - n_seqs, n_seqs * inp->s_copy->nb[0]);
  1489. inp->head = mctx_cur->get_head();
  1490. inp->rs_z = mctx_cur->get_rs_z();
  1491. return inp;
  1492. }
  1493. llm_graph_input_rs * llm_graph_context::build_rs_inp() const {
  1494. const auto * mctx_cur = static_cast<const llama_memory_recurrent_context *>(mctx);
  1495. auto inp = build_rs_inp_impl(ctx0, ubatch, mctx_cur);
  1496. return (llm_graph_input_rs *) res->add_input(std::move(inp));
  1497. }
  1498. ggml_tensor * llm_graph_context::build_rs(
  1499. llm_graph_input_rs * inp,
  1500. ggml_tensor * s,
  1501. int32_t state_size,
  1502. int32_t n_seqs,
  1503. const llm_graph_get_rows_fn & get_state_rows) const {
  1504. const auto * kv_state = inp->mctx;
  1505. return build_rs(s, inp->s_copy_main, inp->s_copy_extra, state_size, n_seqs,
  1506. kv_state->get_n_rs(), kv_state->get_head(), kv_state->get_size(), kv_state->get_rs_z(),
  1507. get_state_rows);
  1508. }
  1509. ggml_tensor * llm_graph_context::build_rwkv_token_shift_load(
  1510. llm_graph_input_rs * inp,
  1511. const llama_ubatch & ubatch,
  1512. int il) const {
  1513. const auto * mctx_cur = static_cast<const llama_memory_recurrent_context *>(mctx);
  1514. const auto token_shift_count = hparams.token_shift_count;
  1515. const int64_t n_seqs = ubatch.n_seqs;
  1516. ggml_tensor * token_shift_all = mctx_cur->get_r_l(il);
  1517. ggml_tensor * token_shift = build_rs(
  1518. inp, token_shift_all,
  1519. hparams.n_embd_r(), n_seqs);
  1520. token_shift = ggml_reshape_3d(ctx0, token_shift, hparams.n_embd, token_shift_count, n_seqs);
  1521. return token_shift;
  1522. }
  1523. ggml_tensor * llm_graph_context::build_rwkv_token_shift_store(
  1524. ggml_tensor * token_shift,
  1525. const llama_ubatch & ubatch,
  1526. int il) const {
  1527. const auto * mctx_cur = static_cast<const llama_memory_recurrent_context *>(mctx);
  1528. const auto token_shift_count = hparams.token_shift_count;
  1529. const auto n_embd = hparams.n_embd;
  1530. const int64_t n_seqs = ubatch.n_seqs;
  1531. const auto kv_head = mctx_cur->get_head();
  1532. return ggml_cpy(
  1533. ctx0,
  1534. ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * token_shift_count, 0),
  1535. ggml_view_1d(ctx0, mctx_cur->get_r_l(il), hparams.n_embd_r()*n_seqs, hparams.n_embd_r()*kv_head*ggml_element_size(mctx_cur->get_r_l(il)))
  1536. );
  1537. }
  1538. llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const {
  1539. const auto * mctx_cur = static_cast<const llama_memory_hybrid_context *>(mctx);
  1540. auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr());
  1541. auto inp_attn = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn());
  1542. auto inp = std::make_unique<llm_graph_input_mem_hybrid>(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur);
  1543. return (llm_graph_input_mem_hybrid *) res->add_input(std::move(inp));
  1544. }
  1545. void llm_graph_context::build_dense_out(
  1546. ggml_tensor * dense_2,
  1547. ggml_tensor * dense_3) const {
  1548. if (!cparams.embeddings || dense_2 == nullptr || dense_3 == nullptr) {
  1549. return;
  1550. }
  1551. ggml_tensor * cur = res->t_embd_pooled != nullptr ? res->t_embd_pooled : res->t_embd;
  1552. GGML_ASSERT(cur != nullptr && "missing t_embd_pooled/t_embd");
  1553. cur = ggml_mul_mat(ctx0, dense_2, cur);
  1554. cur = ggml_mul_mat(ctx0, dense_3, cur);
  1555. cb(cur, "result_embd_pooled", -1);
  1556. res->t_embd_pooled = cur;
  1557. ggml_build_forward_expand(gf, cur);
  1558. }
  1559. void llm_graph_context::build_pooling(
  1560. ggml_tensor * cls,
  1561. ggml_tensor * cls_b,
  1562. ggml_tensor * cls_out,
  1563. ggml_tensor * cls_out_b) const {
  1564. if (!cparams.embeddings) {
  1565. return;
  1566. }
  1567. ggml_tensor * inp = res->t_embd;
  1568. //// find result_norm tensor for input
  1569. //for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  1570. // inp = ggml_graph_node(gf, i);
  1571. // if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  1572. // break;
  1573. // }
  1574. // inp = nullptr;
  1575. //}
  1576. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  1577. ggml_tensor * cur;
  1578. switch (pooling_type) {
  1579. case LLAMA_POOLING_TYPE_NONE:
  1580. {
  1581. cur = inp;
  1582. } break;
  1583. case LLAMA_POOLING_TYPE_MEAN:
  1584. {
  1585. ggml_tensor * inp_mean = build_inp_mean();
  1586. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  1587. } break;
  1588. case LLAMA_POOLING_TYPE_CLS:
  1589. case LLAMA_POOLING_TYPE_LAST:
  1590. {
  1591. ggml_tensor * inp_cls = build_inp_cls();
  1592. cur = ggml_get_rows(ctx0, inp, inp_cls);
  1593. } break;
  1594. case LLAMA_POOLING_TYPE_RANK:
  1595. {
  1596. ggml_tensor * inp_cls = build_inp_cls();
  1597. cur = ggml_get_rows(ctx0, inp, inp_cls);
  1598. // classification head
  1599. // https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566
  1600. if (cls) {
  1601. cur = ggml_mul_mat(ctx0, cls, cur);
  1602. if (cls_b) {
  1603. cur = ggml_add(ctx0, cur, cls_b);
  1604. }
  1605. cur = ggml_tanh(ctx0, cur);
  1606. }
  1607. // some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en
  1608. // https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896
  1609. // Single layer classification head (direct projection)
  1610. // https://github.com/huggingface/transformers/blob/f4fc42216cd56ab6b68270bf80d811614d8d59e4/src/transformers/models/bert/modeling_bert.py#L1476
  1611. if (cls_out) {
  1612. cur = ggml_mul_mat(ctx0, cls_out, cur);
  1613. if (cls_out_b) {
  1614. cur = ggml_add(ctx0, cur, cls_out_b);
  1615. }
  1616. }
  1617. // softmax for qwen3 reranker
  1618. if (arch == LLM_ARCH_QWEN3) {
  1619. cur = ggml_soft_max(ctx0, cur);
  1620. }
  1621. } break;
  1622. default:
  1623. {
  1624. GGML_ABORT("unknown pooling type");
  1625. }
  1626. }
  1627. cb(cur, "result_embd_pooled", -1);
  1628. res->t_embd_pooled = cur;
  1629. ggml_build_forward_expand(gf, cur);
  1630. }
  1631. int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  1632. // TODO move to hparams if a T5 variant appears that uses a different value
  1633. const int64_t max_distance = 128;
  1634. if (bidirectional) {
  1635. n_buckets >>= 1;
  1636. }
  1637. const int64_t max_exact = n_buckets >> 1;
  1638. int32_t relative_position = x - y;
  1639. int32_t relative_bucket = 0;
  1640. if (bidirectional) {
  1641. relative_bucket += (relative_position > 0) * n_buckets;
  1642. relative_position = std::abs(relative_position);
  1643. } else {
  1644. relative_position = -std::min<int32_t>(relative_position, 0);
  1645. }
  1646. int32_t relative_position_if_large = floorf(max_exact + logf(1.0 * relative_position / max_exact) * (n_buckets - max_exact) / log(1.0 * max_distance / max_exact));
  1647. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  1648. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  1649. return relative_bucket;
  1650. }