llama-graph.cpp 66 KB

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