llama-graph.cpp 68 KB

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