llama-graph.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  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-unified.h"
  6. #include "llama-kv-cache-unified-iswa.h"
  7. #include "llama-kv-cache-recurrent.h"
  8. #include <cassert>
  9. #include <cmath>
  10. #include <cstring>
  11. void llm_graph_input_embd::set_input(const llama_ubatch * ubatch) {
  12. if (ubatch->token) {
  13. const int64_t n_tokens = ubatch->n_tokens;
  14. ggml_backend_tensor_set(tokens, ubatch->token, 0, n_tokens*ggml_element_size(tokens));
  15. }
  16. if (ubatch->embd) {
  17. const int64_t n_embd = embd->ne[0];
  18. const int64_t n_tokens = ubatch->n_tokens;
  19. ggml_backend_tensor_set(embd, ubatch->embd, 0, n_tokens*n_embd*ggml_element_size(embd));
  20. }
  21. }
  22. void llm_graph_input_pos::set_input(const llama_ubatch * ubatch) {
  23. if (ubatch->pos && pos) {
  24. const int64_t n_tokens = ubatch->n_tokens;
  25. if (ubatch->token && n_pos_per_embd == 4) {
  26. // in case we're using M-RoPE with text tokens, convert the 1D positions to 4D
  27. // the 3 first dims are the same, and 4th dim is all 0
  28. std::vector<llama_pos> pos_data(n_tokens*n_pos_per_embd);
  29. // copy the first dimension
  30. for (int i = 0; i < n_tokens; ++i) {
  31. pos_data[ i] = ubatch->pos[i];
  32. pos_data[ n_tokens + i] = ubatch->pos[i];
  33. pos_data[2 * n_tokens + i] = ubatch->pos[i];
  34. pos_data[3 * n_tokens + i] = 0; // 4th dim is 0
  35. }
  36. ggml_backend_tensor_set(pos, pos_data.data(), 0, pos_data.size()*ggml_element_size(pos));
  37. } else {
  38. ggml_backend_tensor_set(pos, ubatch->pos, 0, n_tokens*n_pos_per_embd*ggml_element_size(pos));
  39. }
  40. }
  41. }
  42. void llm_graph_input_attn_temp::set_input(const llama_ubatch * ubatch) {
  43. if (ubatch->pos && attn_scale) {
  44. const int64_t n_tokens = ubatch->n_tokens;
  45. std::vector<float> attn_scale_data(n_tokens, 0.0f);
  46. for (int i = 0; i < n_tokens; ++i) {
  47. const float pos = ubatch->pos[i];
  48. attn_scale_data[i] = std::log(
  49. std::floor((pos + 1.0f) / n_attn_temp_floor_scale) + 1.0
  50. ) * f_attn_temp_scale + 1.0;
  51. }
  52. ggml_backend_tensor_set(attn_scale, attn_scale_data.data(), 0, n_tokens*ggml_element_size(attn_scale));
  53. }
  54. }
  55. void llm_graph_input_pos_bucket::set_input(const llama_ubatch * ubatch) {
  56. if (pos_bucket) {
  57. const int64_t n_tokens = ubatch->n_tokens;
  58. GGML_ASSERT(ggml_backend_buffer_is_host(pos_bucket->buffer));
  59. GGML_ASSERT(!ubatch->equal_seqs); // TODO: use ubatch->n_seqs instead of failing
  60. int32_t * data = (int32_t *) pos_bucket->data;
  61. for (int h = 0; h < 1; ++h) {
  62. for (int j = 0; j < n_tokens; ++j) {
  63. for (int i = 0; i < n_tokens; ++i) {
  64. 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);
  65. }
  66. }
  67. }
  68. }
  69. }
  70. void llm_graph_input_pos_bucket_kv::set_input(const llama_ubatch * ubatch) {
  71. if (pos_bucket) {
  72. kv_state->set_input_pos_bucket(pos_bucket, ubatch);
  73. }
  74. }
  75. void llm_graph_input_out_ids::set_input(const llama_ubatch * ubatch) {
  76. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  77. //GGML_ASSERT(out_ids && "every model that can must skip unused outputs");
  78. if (!out_ids) {
  79. LLAMA_LOG_WARN("%s: 'out_ids' is not created\n", __func__);
  80. } else {
  81. const int64_t n_tokens = ubatch->n_tokens;
  82. GGML_ASSERT(ggml_backend_buffer_is_host(out_ids->buffer));
  83. int32_t * data = (int32_t *) out_ids->data;
  84. if (n_outputs == n_tokens) {
  85. for (int i = 0; i < n_tokens; ++i) {
  86. data[i] = i;
  87. }
  88. } else if (ubatch->output) {
  89. int32_t n_outputs = 0;
  90. for (int i = 0; i < n_tokens; ++i) {
  91. if (ubatch->output[i]) {
  92. data[n_outputs++] = i;
  93. }
  94. }
  95. // the graph needs to have been passed the correct number of outputs
  96. GGML_ASSERT(n_outputs == n_outputs);
  97. } else if (n_outputs == 1) {
  98. // only keep last output
  99. data[0] = n_tokens - 1;
  100. } else {
  101. GGML_ASSERT(n_outputs == 0);
  102. }
  103. }
  104. }
  105. }
  106. void llm_graph_input_mean::set_input(const llama_ubatch * ubatch) {
  107. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  108. const int64_t n_tokens = ubatch->n_tokens;
  109. const int64_t n_seq_tokens = ubatch->n_seq_tokens;
  110. const int64_t n_seqs = ubatch->n_seqs;
  111. GGML_ASSERT(mean);
  112. GGML_ASSERT(ggml_backend_buffer_is_host(mean->buffer));
  113. float * data = (float *) mean->data;
  114. memset(mean->data, 0, n_tokens * n_tokens * ggml_element_size(mean));
  115. std::vector<uint64_t> sum(n_tokens, 0);
  116. for (int s = 0; s < n_seqs; ++s) {
  117. const llama_seq_id seq_id = ubatch->seq_id[s][0];
  118. // TODO: adapt limits to n_seqs when ubatch->equal_seqs is true
  119. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  120. sum[seq_id] += ubatch->n_seq_tokens;
  121. }
  122. std::vector<float> div(n_tokens, 0.0f);
  123. for (int i = 0; i < n_tokens; ++i) {
  124. const uint64_t s = sum[i];
  125. if (s > 0) {
  126. div[i] = 1.0f/float(s);
  127. }
  128. }
  129. for (int s = 0; s < n_seqs; ++s) {
  130. const llama_seq_id seq_id = ubatch->seq_id[s][0];
  131. for (int i = 0; i < n_seq_tokens; ++i) {
  132. data[seq_id*n_tokens + s*n_seq_tokens + i] = div[seq_id];
  133. }
  134. }
  135. }
  136. }
  137. void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) {
  138. if (cparams.embeddings && (
  139. cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
  140. cparams.pooling_type == LLAMA_POOLING_TYPE_RANK)) {
  141. const int64_t n_tokens = ubatch->n_tokens;
  142. const int64_t n_seq_tokens = ubatch->n_seq_tokens;
  143. const int64_t n_seqs = ubatch->n_seqs;
  144. GGML_ASSERT(cls);
  145. GGML_ASSERT(ggml_backend_buffer_is_host(cls->buffer));
  146. uint32_t * data = (uint32_t *) cls->data;
  147. memset(cls->data, 0, n_tokens * ggml_element_size(cls));
  148. for (int s = 0; s < n_seqs; ++s) {
  149. const llama_seq_id seq_id = ubatch->seq_id[s][0];
  150. // TODO: adapt limits to n_seqs when ubatch->equal_seqs is true
  151. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS or RANK");
  152. for (int i = 0; i < n_seq_tokens; ++i) {
  153. const llama_pos pos = ubatch->pos[s*n_seq_tokens + i];
  154. if (pos == 0) {
  155. data[seq_id] = s*n_seq_tokens + i;
  156. }
  157. }
  158. }
  159. }
  160. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  161. const int64_t n_tokens = ubatch->n_tokens;
  162. const int64_t n_seq_tokens = ubatch->n_seq_tokens;
  163. const int64_t n_seqs = ubatch->n_seqs;
  164. GGML_ASSERT(cls);
  165. GGML_ASSERT(ggml_backend_buffer_is_host(cls->buffer));
  166. uint32_t * data = (uint32_t *) cls->data;
  167. memset(cls->data, 0, n_tokens * ggml_element_size(cls));
  168. std::vector<int> last_pos(n_tokens, -1);
  169. std::vector<int> last_row(n_tokens, -1);
  170. for (int s = 0; s < n_seqs; ++s) {
  171. const llama_seq_id seq_id = ubatch->seq_id[s][0];
  172. // TODO: adapt limits to n_seqs when ubatch->equal_seqs is true
  173. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  174. for (int i = 0; i < n_seq_tokens; ++i) {
  175. const llama_pos pos = ubatch->pos[s*n_seq_tokens + i];
  176. if (pos >= last_pos[seq_id]) {
  177. last_pos[seq_id] = pos;
  178. last_row[seq_id] = s*n_seq_tokens + i;
  179. }
  180. }
  181. }
  182. for (int i = 0; i < n_tokens; ++i) {
  183. if (last_row[i] >= 0) {
  184. data[i] = last_row[i];
  185. }
  186. }
  187. }
  188. }
  189. void llm_graph_input_s_copy::set_input(const llama_ubatch * ubatch) {
  190. GGML_UNUSED(ubatch);
  191. const int64_t n_kv = kv_state->get_n_kv();
  192. if (s_copy) {
  193. GGML_ASSERT(ggml_backend_buffer_is_host(s_copy->buffer));
  194. int32_t * data = (int32_t *) s_copy->data;
  195. // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
  196. for (uint32_t i = 0; i < n_kv; ++i) {
  197. data[i] = kv_state->s_copy(i);
  198. }
  199. }
  200. }
  201. void llm_graph_input_cross_embd::set_input(const llama_ubatch * ubatch) {
  202. GGML_UNUSED(ubatch);
  203. if (cross_embd && !cross->v_embd.empty()) {
  204. assert(cross_embd->type == GGML_TYPE_F32);
  205. ggml_backend_tensor_set(cross_embd, cross->v_embd.data(), 0, ggml_nbytes(cross_embd));
  206. }
  207. }
  208. void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) {
  209. if (kq_mask) {
  210. if (cparams.causal_attn) {
  211. const int64_t n_kv = ubatch->n_tokens;
  212. const int64_t n_tokens = ubatch->n_tokens;
  213. const int64_t n_seq_tokens = ubatch->n_seq_tokens;
  214. const int64_t n_seqs = ubatch->n_seqs;
  215. GGML_ASSERT(ggml_backend_buffer_is_host(kq_mask->buffer));
  216. float * data = (float *) kq_mask->data;
  217. for (int h = 0; h < 1; ++h) {
  218. for (int s1 = 0; s1 < n_seqs; ++s1) {
  219. const llama_seq_id seq_id = ubatch->seq_id[s1][0];
  220. for (int j = 0; j < n_seq_tokens; ++j) {
  221. const int32_t tj = s1*n_seq_tokens + j;
  222. for (int s0 = 0; s0 < n_seqs; ++s0) {
  223. for (int i = 0; i < n_seq_tokens; ++i) {
  224. const int32_t ti = s0*n_seq_tokens + i;
  225. float f = -INFINITY;
  226. for (int s = 0; s < ubatch->n_seq_id[s0]; ++s) {
  227. if (ubatch->seq_id[s0][s] == seq_id && ubatch->pos[ti] <= ubatch->pos[tj]) {
  228. if (hparams.use_alibi) {
  229. f = -std::abs(ubatch->pos[ti] - ubatch->pos[tj]);
  230. } else {
  231. f = 0.0f;
  232. }
  233. break;
  234. }
  235. }
  236. data[h*(n_kv*n_tokens) + tj*n_kv + ti] = f;
  237. }
  238. }
  239. }
  240. }
  241. }
  242. } else {
  243. const int64_t n_tokens = ubatch->n_tokens;
  244. const int64_t n_seq_tokens = ubatch->n_seq_tokens;
  245. const int64_t n_seqs = ubatch->n_seqs;
  246. const int64_t n_stride = ubatch->n_tokens;
  247. GGML_ASSERT(ggml_backend_buffer_is_host(kq_mask->buffer));
  248. float * data = (float *) kq_mask->data;
  249. for (int h = 0; h < 1; ++h) {
  250. for (int s1 = 0; s1 < n_seqs; ++s1) {
  251. const llama_seq_id seq_id = ubatch->seq_id[s1][0];
  252. for (int j = 0; j < n_seq_tokens; ++j) {
  253. const int32_t tj = s1*n_seq_tokens + j;
  254. for (int s0 = 0; s0 < n_seqs; ++s0) {
  255. for (int i = 0; i < n_seq_tokens; ++i) {
  256. const int32_t ti = s0*n_seq_tokens + i;
  257. float f = -INFINITY;
  258. for (int s = 0; s < ubatch->n_seq_id[s0]; ++s) {
  259. if (ubatch->seq_id[s0][s] == seq_id) {
  260. if (hparams.use_alibi) {
  261. f = -std::abs(ubatch->pos[ti] - ubatch->pos[tj]);
  262. } else {
  263. f = 0.0f;
  264. }
  265. break;
  266. }
  267. }
  268. data[h*(n_tokens*n_tokens) + tj*n_stride + ti] = f;
  269. }
  270. }
  271. for (int i = n_tokens; i < n_stride; ++i) {
  272. data[h*(n_tokens*n_tokens) + tj*n_stride + i] = -INFINITY;
  273. }
  274. }
  275. }
  276. }
  277. }
  278. }
  279. }
  280. void llm_graph_input_attn_kv_unified::set_input(const llama_ubatch * ubatch) {
  281. if (self_kq_mask) {
  282. kv_state->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn);
  283. }
  284. }
  285. void llm_graph_input_attn_kv_unified_iswa::set_input(const llama_ubatch * ubatch) {
  286. if (self_kq_mask) {
  287. kv_state->get_base()->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn);
  288. }
  289. if (self_kq_mask_swa) {
  290. kv_state->get_swa()->set_input_kq_mask(self_kq_mask_swa, ubatch, cparams.causal_attn);
  291. }
  292. }
  293. void llm_graph_input_attn_cross::set_input(const llama_ubatch * ubatch) {
  294. if (cross_kq_mask) {
  295. const int64_t n_enc = cross_kq_mask->ne[0];
  296. const int64_t n_tokens = ubatch->n_tokens;
  297. GGML_ASSERT(ggml_backend_buffer_is_host(cross_kq_mask->buffer));
  298. GGML_ASSERT(!ubatch->equal_seqs); // TODO: use ubatch->n_seqs instead of failing
  299. float * data = (float *) cross_kq_mask->data;
  300. for (int h = 0; h < 1; ++h) {
  301. for (int j = 0; j < n_tokens; ++j) {
  302. for (int i = 0; i < n_enc; ++i) {
  303. float f = -INFINITY;
  304. for (int s = 0; s < ubatch->n_seq_id[j]; ++s) {
  305. const llama_seq_id seq_id = ubatch->seq_id[j][s];
  306. if (cross->seq_ids_enc[i].find(seq_id) != cross->seq_ids_enc[i].end()) {
  307. f = 0.0f;
  308. }
  309. }
  310. data[h*(n_enc*n_tokens) + j*n_enc + i] = f;
  311. }
  312. }
  313. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  314. for (int j = 0; j < n_enc; ++j) {
  315. data[h*(n_enc*n_tokens) + i*n_enc + j] = -INFINITY;
  316. }
  317. }
  318. }
  319. }
  320. }
  321. //
  322. // llm_graph_context
  323. //
  324. llm_graph_context::llm_graph_context(const llm_graph_params & params) :
  325. arch (params.arch),
  326. hparams (params.hparams),
  327. cparams (params.cparams),
  328. ubatch (params.ubatch),
  329. n_embd (hparams.n_embd),
  330. n_layer (hparams.n_layer),
  331. n_rot (hparams.n_rot),
  332. n_ctx (cparams.n_ctx),
  333. n_head (hparams.n_head()),
  334. n_head_kv (hparams.n_head_kv()),
  335. n_embd_head_k (hparams.n_embd_head_k),
  336. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  337. n_embd_head_v (hparams.n_embd_head_v),
  338. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  339. n_expert (hparams.n_expert),
  340. n_expert_used (cparams.warmup ? hparams.n_expert : hparams.n_expert_used),
  341. freq_base (cparams.rope_freq_base),
  342. freq_scale (cparams.rope_freq_scale),
  343. ext_factor (cparams.yarn_ext_factor),
  344. attn_factor (cparams.yarn_attn_factor),
  345. beta_fast (cparams.yarn_beta_fast),
  346. beta_slow (cparams.yarn_beta_slow),
  347. norm_eps (hparams.f_norm_eps),
  348. norm_rms_eps (hparams.f_norm_rms_eps),
  349. n_tokens (ubatch.n_tokens),
  350. n_outputs (params.n_outputs),
  351. n_ctx_orig (cparams.n_ctx_orig_yarn),
  352. pooling_type (cparams.pooling_type),
  353. rope_type (hparams.rope_type),
  354. ctx0 (params.ctx),
  355. sched (params.sched),
  356. backend_cpu (params.backend_cpu),
  357. cvec (params.cvec),
  358. loras (params.loras),
  359. mstate (params.mstate),
  360. cross (params.cross),
  361. cb_func (params.cb),
  362. res (std::make_unique<llm_graph_result>()) {
  363. }
  364. int64_t llm_graph_context::n_pos_per_embd() const {
  365. return hparams.rope_type == LLAMA_ROPE_TYPE_MROPE ? 4 : 1;
  366. }
  367. void llm_graph_context::cb(ggml_tensor * cur, const char * name, int il) const {
  368. if (cb_func) {
  369. cb_func(ubatch, cur, name, il);
  370. }
  371. }
  372. ggml_tensor * llm_graph_context::build_cvec(
  373. ggml_tensor * cur,
  374. int il) const {
  375. return cvec->apply_to(ctx0, cur, il);
  376. }
  377. ggml_tensor * llm_graph_context::build_lora_mm(
  378. ggml_tensor * w,
  379. ggml_tensor * cur) const {
  380. ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  381. for (const auto & lora : *loras) {
  382. llama_adapter_lora_weight * lw = lora.first->get_weight(w);
  383. if (lw == nullptr) {
  384. continue;
  385. }
  386. const float adapter_scale = lora.second;
  387. const float scale = lw->get_scale(lora.first->alpha, adapter_scale);
  388. ggml_tensor * ab_cur = ggml_mul_mat(
  389. ctx0, lw->b,
  390. ggml_mul_mat(ctx0, lw->a, cur)
  391. );
  392. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  393. res = ggml_add(ctx0, res, ab_cur);
  394. }
  395. return res;
  396. }
  397. ggml_tensor * llm_graph_context::build_lora_mm_id(
  398. ggml_tensor * w, // ggml_tensor * as
  399. ggml_tensor * cur, // ggml_tensor * b
  400. ggml_tensor * ids) const {
  401. ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  402. for (const auto & lora : *loras) {
  403. llama_adapter_lora_weight * lw = lora.first->get_weight(w);
  404. if (lw == nullptr) {
  405. continue;
  406. }
  407. const float alpha = lora.first->alpha;
  408. const float rank = (float) lw->b->ne[0];
  409. const float scale = alpha ? lora.second * alpha / rank : lora.second;
  410. ggml_tensor * ab_cur = ggml_mul_mat_id(
  411. ctx0, lw->b,
  412. ggml_mul_mat_id(ctx0, lw->a, cur, ids),
  413. ids
  414. );
  415. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  416. res = ggml_add(ctx0, res, ab_cur);
  417. }
  418. return res;
  419. }
  420. ggml_tensor * llm_graph_context::build_norm(
  421. ggml_tensor * cur,
  422. ggml_tensor * mw,
  423. ggml_tensor * mb,
  424. llm_norm_type type,
  425. int il) const {
  426. switch (type) {
  427. case LLM_NORM: cur = ggml_norm (ctx0, cur, hparams.f_norm_eps); break;
  428. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx0, cur, hparams.f_norm_rms_eps); break;
  429. case LLM_NORM_GROUP:
  430. {
  431. cur = ggml_reshape_3d(ctx0, cur, cur->ne[0], 1, cur->ne[1]);
  432. cur = ggml_group_norm(ctx0, cur, hparams.n_norm_groups, hparams.f_norm_group_eps);
  433. cur = ggml_reshape_2d(ctx0, cur, cur->ne[0], cur->ne[2]);
  434. } break;
  435. }
  436. if (mw || mb) {
  437. cb(cur, "norm", il);
  438. }
  439. if (mw) {
  440. cur = ggml_mul(ctx0, cur, mw);
  441. if (mb) {
  442. cb(cur, "norm_w", il);
  443. }
  444. }
  445. if (mb) {
  446. cur = ggml_add(ctx0, cur, mb);
  447. }
  448. return cur;
  449. }
  450. ggml_tensor * llm_graph_context::build_ffn(
  451. ggml_tensor * cur,
  452. ggml_tensor * up,
  453. ggml_tensor * up_b,
  454. ggml_tensor * up_s,
  455. ggml_tensor * gate,
  456. ggml_tensor * gate_b,
  457. ggml_tensor * gate_s,
  458. ggml_tensor * down,
  459. ggml_tensor * down_b,
  460. ggml_tensor * down_s,
  461. ggml_tensor * act_scales,
  462. llm_ffn_op_type type_op,
  463. llm_ffn_gate_type type_gate,
  464. int il) const {
  465. ggml_tensor * tmp = up ? build_lora_mm(up, cur) : cur;
  466. cb(tmp, "ffn_up", il);
  467. if (up_b) {
  468. tmp = ggml_add(ctx0, tmp, up_b);
  469. cb(tmp, "ffn_up_b", il);
  470. }
  471. if (up_s) {
  472. tmp = ggml_mul(ctx0, tmp, up_s);
  473. cb(tmp, "ffn_up_s", il);
  474. }
  475. if (gate) {
  476. switch (type_gate) {
  477. case LLM_FFN_SEQ:
  478. {
  479. cur = build_lora_mm(gate, tmp);
  480. cb(cur, "ffn_gate", il);
  481. } break;
  482. case LLM_FFN_PAR:
  483. {
  484. cur = build_lora_mm(gate, cur);
  485. cb(cur, "ffn_gate", il);
  486. } break;
  487. }
  488. if (gate_b) {
  489. cur = ggml_add(ctx0, cur, gate_b);
  490. cb(cur, "ffn_gate_b", il);
  491. }
  492. if (gate_s) {
  493. cur = ggml_mul(ctx0, cur, gate_s);
  494. cb(cur, "ffn_gate_s", il);
  495. }
  496. } else {
  497. cur = tmp;
  498. }
  499. switch (type_op) {
  500. case LLM_FFN_SILU:
  501. {
  502. cur = ggml_silu(ctx0, cur);
  503. cb(cur, "ffn_silu", il);
  504. } break;
  505. case LLM_FFN_GELU:
  506. {
  507. cur = ggml_gelu(ctx0, cur);
  508. cb(cur, "ffn_gelu", il);
  509. if (act_scales != NULL) {
  510. cur = ggml_div(ctx0, cur, act_scales);
  511. cb(cur, "ffn_act", il);
  512. }
  513. } break;
  514. case LLM_FFN_RELU:
  515. {
  516. cur = ggml_relu(ctx0, cur);
  517. cb(cur, "ffn_relu", il);
  518. } break;
  519. case LLM_FFN_RELU_SQR:
  520. {
  521. cur = ggml_relu(ctx0, cur);
  522. cb(cur, "ffn_relu", il);
  523. cur = ggml_sqr(ctx0, cur);
  524. cb(cur, "ffn_sqr(relu)", il);
  525. } break;
  526. case LLM_FFN_SWIGLU:
  527. {
  528. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  529. int64_t split_point = cur->ne[0] / 2;
  530. // TODO: these conts should not be needed, see https://github.com/ggml-org/llama.cpp/pull/14090#discussion_r2137437217
  531. ggml_tensor * x0 = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, split_point, cur->ne[1], cur->nb[1], 0));
  532. ggml_tensor * x1 = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, split_point, cur->ne[1], cur->nb[1], split_point * ggml_element_size(cur)));
  533. x0 = ggml_silu(ctx0, x0);
  534. cb(cur, "ffn_silu", il);
  535. cur = ggml_mul(ctx0, x0, x1);
  536. cb(cur, "ffn_mul", il);
  537. } break;
  538. case LLM_FFN_GEGLU:
  539. {
  540. // Split into two equal parts
  541. int64_t split_point = cur->ne[0] / 2;
  542. // TODO: these conts should not be needed, see https://github.com/ggml-org/llama.cpp/pull/14090#discussion_r2137437217
  543. ggml_tensor * x0 = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, split_point, cur->ne[1], cur->nb[1], 0));
  544. ggml_tensor * x1 = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, split_point, cur->ne[1], cur->nb[1], split_point * ggml_element_size(cur)));
  545. x0 = ggml_gelu(ctx0, x0);
  546. cb(x0, "ffn_gelu", il);
  547. cur = ggml_mul(ctx0, x0, x1);
  548. cb(cur, "ffn_geglu", il);
  549. } break;
  550. }
  551. if (gate && type_gate == LLM_FFN_PAR) {
  552. cur = ggml_mul(ctx0, cur, tmp);
  553. cb(cur, "ffn_gate_par", il);
  554. }
  555. if (down) {
  556. cur = build_lora_mm(down, cur);
  557. if (arch == LLM_ARCH_GLM4) {
  558. // GLM4 seems to have numerical issues with half-precision accumulators
  559. ggml_mul_mat_set_prec(cur, GGML_PREC_F32);
  560. }
  561. }
  562. if (down_b) {
  563. cb(cur, "ffn_down", il);
  564. }
  565. if (down_b) {
  566. cur = ggml_add(ctx0, cur, down_b);
  567. }
  568. if (down_s) {
  569. cur = ggml_mul(ctx0, cur, down_s);
  570. cb(cur, "ffn_down_s", il);
  571. }
  572. return cur;
  573. }
  574. ggml_tensor * llm_graph_context::build_moe_ffn(
  575. ggml_tensor * cur,
  576. ggml_tensor * gate_inp,
  577. ggml_tensor * up_exps,
  578. ggml_tensor * gate_exps,
  579. ggml_tensor * down_exps,
  580. ggml_tensor * exp_probs_b,
  581. int64_t n_expert,
  582. int64_t n_expert_used,
  583. llm_ffn_op_type type_op,
  584. bool norm_w,
  585. bool scale_w,
  586. float w_scale,
  587. llama_expert_gating_func_type gating_op,
  588. int il) const {
  589. const int64_t n_embd = cur->ne[0];
  590. const int64_t n_tokens = cur->ne[1];
  591. const bool weight_before_ffn = arch == LLM_ARCH_LLAMA4; // for llama4, we apply the sigmoid-ed weights before the FFN
  592. ggml_tensor * logits = build_lora_mm(gate_inp, cur); // [n_expert, n_tokens]
  593. cb(logits, "ffn_moe_logits", il);
  594. ggml_tensor * probs = nullptr;
  595. switch (gating_op) {
  596. case LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX:
  597. {
  598. probs = ggml_soft_max(ctx0, logits); // [n_expert, n_tokens]
  599. } break;
  600. case LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID:
  601. {
  602. probs = ggml_sigmoid(ctx0, logits); // [n_expert, n_tokens]
  603. } break;
  604. default:
  605. GGML_ABORT("fatal error");
  606. }
  607. cb(probs, "ffn_moe_probs", il);
  608. // add experts selection bias - introduced in DeepSeek V3
  609. // leave probs unbiased as it's later used to get expert weights
  610. ggml_tensor * selection_probs = probs;
  611. if (exp_probs_b != nullptr) {
  612. selection_probs = ggml_add(ctx0, probs, exp_probs_b);
  613. cb(selection_probs, "ffn_moe_probs_biased", il);
  614. }
  615. // llama4 doesn't have exp_probs_b, and sigmoid is only used after top_k
  616. // see: https://github.com/meta-llama/llama-models/blob/699a02993512fb36936b1b0741e13c06790bcf98/models/llama4/moe.py#L183-L198
  617. if (arch == LLM_ARCH_LLAMA4) {
  618. selection_probs = logits;
  619. }
  620. // select experts
  621. ggml_tensor * selected_experts = ggml_top_k(ctx0, selection_probs, n_expert_used); // [n_expert_used, n_tokens]
  622. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  623. cb(selected_experts, "ffn_moe_topk", il);
  624. ggml_tensor * weights = ggml_get_rows(ctx0,
  625. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  626. cb(weights, "ffn_moe_weights", il);
  627. if (norm_w) {
  628. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens);
  629. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights); // [1, n_tokens]
  630. cb(weights_sum, "ffn_moe_weights_sum", il);
  631. weights = ggml_div(ctx0, weights, weights_sum); // [n_expert_used, n_tokens]
  632. cb(weights, "ffn_moe_weights_norm", il);
  633. weights = ggml_reshape_3d(ctx0, weights, 1, n_expert_used, n_tokens);
  634. }
  635. if (scale_w) {
  636. weights = ggml_scale(ctx0, weights, w_scale);
  637. cb(weights, "ffn_moe_weights_scaled", il);
  638. }
  639. cur = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens);
  640. if (weight_before_ffn) {
  641. // repeat cur to [n_embd, n_expert_used, n_tokens]
  642. ggml_tensor * repeated = ggml_repeat_4d(ctx0, cur, n_embd, n_expert_used, n_tokens, 1);
  643. cur = ggml_mul(ctx0, repeated, weights);
  644. cb(cur, "ffn_moe_weighted", il);
  645. }
  646. ggml_tensor * up = build_lora_mm_id(up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  647. cb(up, "ffn_moe_up", il);
  648. ggml_tensor * experts = nullptr;
  649. if (gate_exps) {
  650. cur = build_lora_mm_id(gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  651. cb(cur, "ffn_moe_gate", il);
  652. } else {
  653. cur = up;
  654. }
  655. switch (type_op) {
  656. case LLM_FFN_SILU:
  657. {
  658. cur = ggml_silu(ctx0, cur);
  659. cb(cur, "ffn_moe_silu", il);
  660. } break;
  661. case LLM_FFN_GELU:
  662. {
  663. cur = ggml_gelu(ctx0, cur);
  664. cb(cur, "ffn_moe_gelu", il);
  665. } break;
  666. default:
  667. GGML_ABORT("fatal error");
  668. }
  669. if (gate_exps) {
  670. cur = ggml_mul(ctx0, cur, up); // [n_ff, n_expert_used, n_tokens]
  671. cb(cur, "ffn_moe_gate_par", il);
  672. }
  673. experts = build_lora_mm_id(down_exps, cur, selected_experts); // [n_embd, n_expert_used, n_tokens]
  674. cb(experts, "ffn_moe_down", il);
  675. if (!weight_before_ffn) {
  676. experts = ggml_mul(ctx0, experts, weights);
  677. cb(cur, "ffn_moe_weighted", il);
  678. }
  679. // aggregate experts
  680. ggml_tensor * moe_out = nullptr;
  681. for (int i = 0; i < n_expert_used; ++i) {
  682. ggml_tensor * cur_expert = ggml_view_2d(ctx0, experts, n_embd, n_tokens,
  683. experts->nb[2], i*experts->nb[1]);
  684. if (i == 0) {
  685. moe_out = cur_expert;
  686. } else {
  687. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  688. }
  689. }
  690. if (n_expert_used == 1) {
  691. // avoid returning a non-contiguous tensor
  692. moe_out = ggml_cont(ctx0, moe_out);
  693. }
  694. cb(moe_out, "ffn_moe_out", il);
  695. return moe_out;
  696. }
  697. // input embeddings with optional lora
  698. ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd) const {
  699. const int64_t n_embd = hparams.n_embd;
  700. auto inp = std::make_unique<llm_graph_input_embd>();
  701. ggml_tensor * cur = nullptr;
  702. if (ubatch.token) {
  703. inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_tokens);
  704. //cb(inp->tokens, "inp_tokens", -1);
  705. ggml_set_input(inp->tokens);
  706. res->t_tokens = inp->tokens;
  707. cur = ggml_get_rows(ctx0, tok_embd, inp->tokens);
  708. // apply lora for embedding tokens if needed
  709. for (const auto & lora : *loras) {
  710. llama_adapter_lora_weight * lw = lora.first->get_weight(tok_embd);
  711. if (lw == nullptr) {
  712. continue;
  713. }
  714. const float adapter_scale = lora.second;
  715. const float scale = lw->get_scale(lora.first->alpha, adapter_scale);
  716. ggml_tensor * inpL_delta = ggml_scale(ctx0, ggml_mul_mat(
  717. ctx0, lw->b, // non-transposed lora_b
  718. ggml_get_rows(ctx0, lw->a, inp->tokens)
  719. ), scale);
  720. cur = ggml_add(ctx0, cur, inpL_delta);
  721. }
  722. } else {
  723. inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, ubatch.n_tokens);
  724. ggml_set_input(inp->embd);
  725. cur = inp->embd;
  726. }
  727. // For Granite architecture
  728. if (hparams.f_embedding_scale != 0.0f) {
  729. cur = ggml_scale(ctx0, cur, hparams.f_embedding_scale);
  730. }
  731. cb(cur, "inp_embd", -1);
  732. res->add_input(std::move(inp));
  733. return cur;
  734. }
  735. ggml_tensor * llm_graph_context::build_inp_pos() const {
  736. auto inp = std::make_unique<llm_graph_input_pos>(n_pos_per_embd());
  737. auto & cur = inp->pos;
  738. cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens*n_pos_per_embd());
  739. ggml_set_input(cur);
  740. res->add_input(std::move(inp));
  741. return cur;
  742. }
  743. ggml_tensor * llm_graph_context::build_inp_attn_scale() const {
  744. auto inp = std::make_unique<llm_graph_input_attn_temp>(hparams.n_attn_temp_floor_scale, hparams.f_attn_temp_scale);
  745. auto & cur = inp->attn_scale;
  746. // this need to be 1x1xN for broadcasting
  747. cur = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 1, 1, n_tokens);
  748. ggml_set_input(cur);
  749. res->add_input(std::move(inp));
  750. return cur;
  751. }
  752. ggml_tensor * llm_graph_context::build_inp_out_ids() const {
  753. auto inp = std::make_unique<llm_graph_input_out_ids>(hparams, cparams, n_outputs);
  754. auto & cur = inp->out_ids;
  755. cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  756. ggml_set_input(cur);
  757. res->add_input(std::move(inp));
  758. return cur;
  759. }
  760. ggml_tensor * llm_graph_context::build_inp_mean() const {
  761. auto inp = std::make_unique<llm_graph_input_mean>(cparams);
  762. auto & cur = inp->mean;
  763. cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  764. ggml_set_input(cur);
  765. res->add_input(std::move(inp));
  766. return cur;
  767. }
  768. ggml_tensor * llm_graph_context::build_inp_cls() const {
  769. auto inp = std::make_unique<llm_graph_input_cls>(cparams);
  770. auto & cur = inp->cls;
  771. cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  772. ggml_set_input(cur);
  773. res->add_input(std::move(inp));
  774. return cur;
  775. }
  776. ggml_tensor * llm_graph_context::build_inp_s_copy() const {
  777. const auto * kv_state = static_cast<const llama_kv_cache_recurrent_state *>(mstate);
  778. auto inp = std::make_unique<llm_graph_input_s_copy>(kv_state);
  779. const auto n_kv = kv_state->get_n_kv();
  780. auto & cur = inp->s_copy;
  781. cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_kv);
  782. ggml_set_input(cur);
  783. res->add_input(std::move(inp));
  784. return cur;
  785. }
  786. ggml_tensor * llm_graph_context::build_inp_cross_embd() const {
  787. auto inp = std::make_unique<llm_graph_input_cross_embd>(cross);
  788. auto & cur = inp->cross_embd;
  789. // if we have the output embeddings from the encoder, use them directly
  790. // TODO: needs more work to be correct, for now just use the tensor shape
  791. //if (cross->t_embd) {
  792. // cur = ggml_view_tensor(ctx0, cross->t_embd);
  793. // return cur;
  794. //}
  795. const auto n_embd = !cross->v_embd.empty() ? cross->n_embd : hparams.n_embd;
  796. const auto n_enc = !cross->v_embd.empty() ? cross->n_enc : hparams.n_ctx_train;
  797. cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_enc);
  798. ggml_set_input(cur);
  799. res->add_input(std::move(inp));
  800. return cur;
  801. }
  802. ggml_tensor * llm_graph_context::build_inp_pos_bucket_enc() const {
  803. auto inp = std::make_unique<llm_graph_input_pos_bucket>(hparams);
  804. auto & cur = inp->pos_bucket;
  805. cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  806. ggml_set_input(cur);
  807. res->add_input(std::move(inp));
  808. return cur;
  809. }
  810. ggml_tensor * llm_graph_context::build_inp_pos_bucket_dec() const {
  811. const auto * kv_state = static_cast<const llama_kv_cache_unified_state *>(mstate);
  812. auto inp = std::make_unique<llm_graph_input_pos_bucket_kv>(hparams, kv_state);
  813. const auto n_kv = kv_state->get_n_kv();
  814. auto & cur = inp->pos_bucket;
  815. cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  816. ggml_set_input(cur);
  817. res->add_input(std::move(inp));
  818. return cur;
  819. }
  820. ggml_tensor * llm_graph_context::build_pos_bias(ggml_tensor * pos_bucket, ggml_tensor * attn_rel_b) const {
  821. ggml_tensor * pos_bucket_1d = ggml_reshape_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1]);
  822. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  823. ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  824. pos_bias = ggml_reshape_3d(ctx0, pos_bias, pos_bias->ne[0], pos_bucket->ne[0], pos_bucket->ne[1]);
  825. pos_bias = ggml_permute (ctx0, pos_bias, 2, 0, 1, 3);
  826. pos_bias = ggml_cont (ctx0, pos_bias);
  827. cb(pos_bias, "pos_bias", -1);
  828. return pos_bias;
  829. }
  830. ggml_tensor * llm_graph_context::build_attn_mha(
  831. ggml_cgraph * gf,
  832. ggml_tensor * q,
  833. ggml_tensor * k,
  834. ggml_tensor * v,
  835. ggml_tensor * kq_b,
  836. ggml_tensor * kq_mask,
  837. ggml_tensor * v_mla,
  838. float kq_scale) const {
  839. const bool v_trans = v->nb[1] > v->nb[2];
  840. q = ggml_permute(ctx0, q, 0, 2, 1, 3);
  841. k = ggml_permute(ctx0, k, 0, 2, 1, 3);
  842. v = ggml_permute(ctx0, v, 0, 2, 1, 3);
  843. const auto n_tokens = q->ne[1];
  844. const auto n_head = q->ne[2];
  845. const auto n_kv = k->ne[1];
  846. ggml_tensor * cur;
  847. // TODO: replace hardcoded padding with ggml-provided padding
  848. if (cparams.flash_attn && (n_kv % 256 == 0) && kq_b == nullptr) {
  849. GGML_ASSERT(kq_b == nullptr && "Flash attention does not support KQ bias yet");
  850. if (v_trans) {
  851. v = ggml_transpose(ctx0, v);
  852. }
  853. // this can happen when KV cache is not used (e.g. an embedding model with non-causal attn)
  854. if (k->type == GGML_TYPE_F32) {
  855. k = ggml_cast(ctx0, k, GGML_TYPE_F16);
  856. }
  857. if (v->type == GGML_TYPE_F32) {
  858. v = ggml_cast(ctx0, v, GGML_TYPE_F16);
  859. }
  860. cur = ggml_flash_attn_ext(ctx0, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias,
  861. hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f);
  862. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  863. if (v_mla) {
  864. #if 0
  865. // v_mla can be applied as a matrix-vector multiplication with broadcasting across dimension 3 == n_tokens.
  866. // However, the code is optimized for dimensions 0 and 1 being large, so this is ineffient.
  867. cur = ggml_reshape_4d(ctx0, cur, v_mla->ne[0], 1, n_head, n_tokens);
  868. cur = ggml_mul_mat(ctx0, v_mla, cur);
  869. #else
  870. // It's preferable to do the calculation as a matrix-matrix multiplication with n_tokens in dimension 1.
  871. // The permutations are noops and only change how the tensor data is interpreted.
  872. cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
  873. cur = ggml_mul_mat(ctx0, v_mla, cur);
  874. cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
  875. cur = ggml_cont(ctx0, cur); // Needed because ggml_reshape_2d expects contiguous inputs.
  876. #endif
  877. }
  878. cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*n_head, n_tokens);
  879. } else {
  880. ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  881. // note: this op tends to require high floating point range
  882. // while for some models F16 is enough, for others it is not, so we default to F32 here
  883. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  884. if (arch == LLM_ARCH_GROK) {
  885. // need to do the following:
  886. // multiply by attn_output_multiplyer of 0.08838834764831845
  887. // and then :
  888. // kq = 30 * tanh(kq / 30)
  889. // before the softmax below
  890. kq = ggml_tanh(ctx0, ggml_scale(ctx0, kq, 0.08838834764831845f/30.0f));
  891. kq = ggml_scale(ctx0, kq, 30);
  892. }
  893. if (hparams.attn_soft_cap) {
  894. kq = ggml_scale(ctx0, kq, 1.0f / hparams.f_attn_logit_softcapping);
  895. kq = ggml_tanh (ctx0, kq);
  896. kq = ggml_scale(ctx0, kq, hparams.f_attn_logit_softcapping);
  897. }
  898. if (kq_b) {
  899. kq = ggml_add(ctx0, kq, kq_b);
  900. }
  901. kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  902. if (!v_trans) {
  903. // note: avoid this branch
  904. v = ggml_cont(ctx0, ggml_transpose(ctx0, v));
  905. }
  906. ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  907. // for MLA with the absorption optimization, we need to "decompress" from MQA back to MHA
  908. if (v_mla) {
  909. kqv = ggml_mul_mat(ctx0, v_mla, kqv);
  910. }
  911. cur = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  912. cur = ggml_cont_2d(ctx0, cur, cur->ne[0]*n_head, n_tokens);
  913. if (!cparams.offload_kqv) {
  914. // all nodes between the KV store and the attention output are run on the CPU
  915. ggml_backend_sched_set_tensor_backend(sched, cur, backend_cpu);
  916. }
  917. }
  918. ggml_build_forward_expand(gf, cur);
  919. return cur;
  920. }
  921. llm_graph_input_attn_no_cache * llm_graph_context::build_attn_inp_no_cache() const {
  922. auto inp = std::make_unique<llm_graph_input_attn_no_cache>(hparams, cparams);
  923. // note: there is no KV cache, so the number of KV values is equal to the number of tokens in the batch
  924. inp->kq_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  925. //cb(inp_kq_mask, "KQ_mask", -1);
  926. ggml_set_input(inp->kq_mask);
  927. inp->kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->kq_mask, GGML_TYPE_F16) : inp->kq_mask;
  928. return (llm_graph_input_attn_no_cache *) res->add_input(std::move(inp));
  929. }
  930. ggml_tensor * llm_graph_context::build_attn(
  931. llm_graph_input_attn_no_cache * inp,
  932. ggml_cgraph * gf,
  933. ggml_tensor * wo,
  934. ggml_tensor * wo_b,
  935. ggml_tensor * q_cur,
  936. ggml_tensor * k_cur,
  937. ggml_tensor * v_cur,
  938. ggml_tensor * kq_b,
  939. ggml_tensor * v_mla,
  940. float kq_scale,
  941. int il) const {
  942. GGML_UNUSED(n_tokens);
  943. // these nodes are added to the graph together so that they are not reordered
  944. // by doing so, the number of splits in the graph is reduced
  945. ggml_build_forward_expand(gf, q_cur);
  946. ggml_build_forward_expand(gf, k_cur);
  947. ggml_build_forward_expand(gf, v_cur);
  948. const auto & kq_mask = inp->get_kq_mask();
  949. ggml_tensor * q = q_cur;
  950. ggml_tensor * k = k_cur;
  951. ggml_tensor * v = v_cur;
  952. ggml_tensor * cur = build_attn_mha(gf, q, k, v, kq_b, kq_mask, v_mla, kq_scale);
  953. cb(cur, "kqv_out", il);
  954. if (wo) {
  955. cur = build_lora_mm(wo, cur);
  956. }
  957. if (wo_b) {
  958. //cb(cur, "kqv_wo", il);
  959. }
  960. if (wo_b) {
  961. cur = ggml_add(ctx0, cur, wo_b);
  962. }
  963. return cur;
  964. }
  965. llm_graph_input_attn_kv_unified * llm_graph_context::build_attn_inp_kv_unified() const {
  966. const auto * kv_state = static_cast<const llama_kv_cache_unified_state *>(mstate);
  967. auto inp = std::make_unique<llm_graph_input_attn_kv_unified>(hparams, cparams, kv_state);
  968. {
  969. GGML_ASSERT(hparams.swa_type == LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache_unified_iswa for SWA");
  970. const auto n_kv = kv_state->get_n_kv();
  971. inp->self_kq_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  972. //cb(inp->self_kq_mask, "KQ_mask", -1);
  973. ggml_set_input(inp->self_kq_mask);
  974. inp->self_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask, GGML_TYPE_F16) : inp->self_kq_mask;
  975. }
  976. return (llm_graph_input_attn_kv_unified *) res->add_input(std::move(inp));
  977. }
  978. ggml_tensor * llm_graph_context::build_attn(
  979. llm_graph_input_attn_kv_unified * inp,
  980. ggml_cgraph * gf,
  981. ggml_tensor * wo,
  982. ggml_tensor * wo_b,
  983. ggml_tensor * q_cur,
  984. ggml_tensor * k_cur,
  985. ggml_tensor * v_cur,
  986. ggml_tensor * kq_b,
  987. ggml_tensor * v_mla,
  988. float kq_scale,
  989. int il) const {
  990. // these nodes are added to the graph together so that they are not reordered
  991. // by doing so, the number of splits in the graph is reduced
  992. ggml_build_forward_expand(gf, q_cur);
  993. ggml_build_forward_expand(gf, k_cur);
  994. ggml_build_forward_expand(gf, v_cur);
  995. const auto * kv_state = static_cast<const llama_kv_cache_unified_state *>(mstate);
  996. // store to KV cache
  997. {
  998. ggml_build_forward_expand(gf, kv_state->cpy_k(ctx0, k_cur, il));
  999. ggml_build_forward_expand(gf, kv_state->cpy_v(ctx0, v_cur, il));
  1000. }
  1001. const auto & kq_mask = inp->get_kq_mask();
  1002. ggml_tensor * q = q_cur;
  1003. ggml_tensor * k = kv_state->get_k(ctx0, il);
  1004. ggml_tensor * v = kv_state->get_v(ctx0, il);
  1005. ggml_tensor * cur = build_attn_mha(gf, q, k, v, kq_b, kq_mask, v_mla, kq_scale);
  1006. cb(cur, "kqv_out", il);
  1007. if (wo) {
  1008. cur = build_lora_mm(wo, cur);
  1009. if (arch == LLM_ARCH_GLM4) {
  1010. // GLM4 seems to have numerical issues with half-precision accumulators
  1011. ggml_mul_mat_set_prec(cur, GGML_PREC_F32);
  1012. }
  1013. }
  1014. if (wo_b) {
  1015. cur = ggml_add(ctx0, cur, wo_b);
  1016. }
  1017. return cur;
  1018. }
  1019. llm_graph_input_attn_kv_unified_iswa * llm_graph_context::build_attn_inp_kv_unified_iswa() const {
  1020. const auto * kv_state = static_cast<const llama_kv_cache_unified_iswa_state *>(mstate);
  1021. auto inp = std::make_unique<llm_graph_input_attn_kv_unified_iswa>(hparams, cparams, kv_state);
  1022. {
  1023. const auto n_kv = kv_state->get_base()->get_n_kv();
  1024. inp->self_kq_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  1025. //cb(inp->self_kq_mask, "KQ_mask", -1);
  1026. ggml_set_input(inp->self_kq_mask);
  1027. inp->self_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask, GGML_TYPE_F16) : inp->self_kq_mask;
  1028. }
  1029. {
  1030. GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache_unified for non-SWA");
  1031. const auto n_kv = kv_state->get_swa()->get_n_kv();
  1032. inp->self_kq_mask_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  1033. //cb(inp->self_kq_mask_swa, "KQ_mask_swa", -1);
  1034. ggml_set_input(inp->self_kq_mask_swa);
  1035. 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;
  1036. }
  1037. return (llm_graph_input_attn_kv_unified_iswa *) res->add_input(std::move(inp));
  1038. }
  1039. ggml_tensor * llm_graph_context::build_attn(
  1040. llm_graph_input_attn_kv_unified_iswa * inp,
  1041. ggml_cgraph * gf,
  1042. ggml_tensor * wo,
  1043. ggml_tensor * wo_b,
  1044. ggml_tensor * q_cur,
  1045. ggml_tensor * k_cur,
  1046. ggml_tensor * v_cur,
  1047. ggml_tensor * kq_b,
  1048. ggml_tensor * v_mla,
  1049. float kq_scale,
  1050. int il) const {
  1051. // these nodes are added to the graph together so that they are not reordered
  1052. // by doing so, the number of splits in the graph is reduced
  1053. ggml_build_forward_expand(gf, q_cur);
  1054. ggml_build_forward_expand(gf, k_cur);
  1055. ggml_build_forward_expand(gf, v_cur);
  1056. const auto * kv_state_iswa = static_cast<const llama_kv_cache_unified_iswa_state *>(mstate);
  1057. const bool is_swa = hparams.is_swa(il);
  1058. const auto * kv_state = is_swa ? kv_state_iswa->get_swa() : kv_state_iswa->get_base();
  1059. // store to KV cache
  1060. {
  1061. ggml_build_forward_expand(gf, kv_state->cpy_k(ctx0, k_cur, il));
  1062. ggml_build_forward_expand(gf, kv_state->cpy_v(ctx0, v_cur, il));
  1063. }
  1064. const auto & kq_mask = is_swa ? inp->get_kq_mask_swa() : inp->get_kq_mask();
  1065. ggml_tensor * q = q_cur;
  1066. ggml_tensor * k = kv_state->get_k(ctx0, il);
  1067. ggml_tensor * v = kv_state->get_v(ctx0, il);
  1068. ggml_tensor * cur = build_attn_mha(gf, q, k, v, kq_b, kq_mask, v_mla, kq_scale);
  1069. cb(cur, "kqv_out", il);
  1070. if (wo) {
  1071. cur = build_lora_mm(wo, cur);
  1072. }
  1073. if (wo_b) {
  1074. //cb(cur, "kqv_wo", il);
  1075. }
  1076. if (wo_b) {
  1077. cur = ggml_add(ctx0, cur, wo_b);
  1078. }
  1079. return cur;
  1080. }
  1081. llm_graph_input_attn_cross * llm_graph_context::build_attn_inp_cross() const {
  1082. auto inp = std::make_unique<llm_graph_input_attn_cross>(cross);
  1083. const int32_t n_enc = !cross->v_embd.empty() ? cross->n_enc : hparams.n_ctx_train;
  1084. inp->cross_kq_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  1085. ggml_set_input(inp->cross_kq_mask);
  1086. inp->cross_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->cross_kq_mask, GGML_TYPE_F16) : inp->cross_kq_mask;
  1087. return (llm_graph_input_attn_cross *) res->add_input(std::move(inp));
  1088. }
  1089. ggml_tensor * llm_graph_context::build_attn(
  1090. llm_graph_input_attn_cross * inp,
  1091. ggml_cgraph * gf,
  1092. ggml_tensor * wo,
  1093. ggml_tensor * wo_b,
  1094. ggml_tensor * q_cur,
  1095. ggml_tensor * k_cur,
  1096. ggml_tensor * v_cur,
  1097. ggml_tensor * kq_b,
  1098. ggml_tensor * v_mla,
  1099. float kq_scale,
  1100. int il) const {
  1101. // these nodes are added to the graph together so that they are not reordered
  1102. // by doing so, the number of splits in the graph is reduced
  1103. ggml_build_forward_expand(gf, q_cur);
  1104. ggml_build_forward_expand(gf, k_cur);
  1105. ggml_build_forward_expand(gf, v_cur);
  1106. const auto & kq_mask = inp->get_kq_mask_cross();
  1107. ggml_tensor * q = q_cur;
  1108. ggml_tensor * k = k_cur;
  1109. ggml_tensor * v = v_cur;
  1110. ggml_tensor * cur = build_attn_mha(gf, q, k, v, kq_b, kq_mask, v_mla, kq_scale);
  1111. cb(cur, "kqv_out", il);
  1112. if (wo) {
  1113. cur = build_lora_mm(wo, cur);
  1114. }
  1115. if (wo_b) {
  1116. //cb(cur, "kqv_wo", il);
  1117. }
  1118. if (wo_b) {
  1119. cur = ggml_add(ctx0, cur, wo_b);
  1120. }
  1121. return cur;
  1122. }
  1123. ggml_tensor * llm_graph_context::build_recurrent_state(
  1124. ggml_cgraph * gf,
  1125. ggml_tensor * s,
  1126. ggml_tensor * state_copy,
  1127. int32_t state_size,
  1128. int32_t n_seqs,
  1129. bool avoid_copies) const {
  1130. const auto * kv_state = static_cast<const llama_kv_cache_recurrent_state *>(mstate);
  1131. const auto n_kv = kv_state->get_n_kv();
  1132. const auto kv_head = kv_state->get_head();
  1133. const auto rs_zero = kv_state->get_rs_z();
  1134. ggml_tensor * states = ggml_reshape_2d(ctx0, s, state_size, kv_state->get_size());
  1135. // Clear a single state which will then be copied to the other cleared states.
  1136. // Note that this is a no-op when the view is zero-sized.
  1137. ggml_tensor * state_zero = ggml_view_1d(ctx0, states, state_size*(rs_zero >= 0), rs_zero*states->nb[1]*(rs_zero >= 0));
  1138. ggml_build_forward_expand(gf, ggml_scale_inplace(ctx0, state_zero, 0));
  1139. ggml_tensor * output_states;
  1140. if (!avoid_copies) {
  1141. // copy states
  1142. // NOTE: assuming the copy destinations are ALL contained between kv_head and kv_head + n_kv
  1143. // {state_size, kv_size} -> {state_size, n_seqs}
  1144. output_states = ggml_get_rows(ctx0, states, ggml_view_1d(ctx0, state_copy, n_seqs, 0));
  1145. ggml_build_forward_expand(gf, output_states);
  1146. } else {
  1147. // FIXME: make the gathering operation happen before the copy below
  1148. // (maybe with an optional lambda function passed as a parameter instead of `avoid_copies`?)
  1149. output_states = states;
  1150. }
  1151. // copy extra states which won't be changed further (between n_seqs and n_kv)
  1152. ggml_tensor * states_extra = ggml_get_rows(ctx0, states, ggml_view_1d(ctx0, state_copy, n_kv - n_seqs, n_seqs*state_copy->nb[0]));
  1153. ggml_build_forward_expand(gf,
  1154. ggml_cpy(ctx0,
  1155. states_extra,
  1156. ggml_view_1d(ctx0, s, state_size*(n_kv - n_seqs), (kv_head + n_seqs)*state_size*ggml_element_size(s))));
  1157. return output_states;
  1158. }
  1159. ggml_tensor * llm_graph_context::build_rwkv_token_shift_load(
  1160. ggml_cgraph * gf,
  1161. ggml_tensor * state_copy,
  1162. const llama_ubatch & ubatch,
  1163. int il) const {
  1164. const auto * kv_state = static_cast<const llama_kv_cache_recurrent_state *>(mstate);
  1165. const auto token_shift_count = hparams.token_shift_count;
  1166. const int64_t n_seqs = ubatch.n_seqs;
  1167. ggml_tensor * token_shift_all = kv_state->get_k_l(il);
  1168. ggml_tensor * token_shift = build_recurrent_state(
  1169. gf, token_shift_all, state_copy,
  1170. hparams.n_embd_k_s(), n_seqs);
  1171. token_shift = ggml_reshape_3d(ctx0, token_shift, hparams.n_embd, token_shift_count, n_seqs);
  1172. return token_shift;
  1173. }
  1174. ggml_tensor * llm_graph_context::build_rwkv_token_shift_store(
  1175. ggml_tensor * token_shift,
  1176. const llama_ubatch & ubatch,
  1177. int il) const {
  1178. const auto * kv_state = static_cast<const llama_kv_cache_recurrent_state *>(mstate);
  1179. const auto token_shift_count = hparams.token_shift_count;
  1180. const auto n_embd = hparams.n_embd;
  1181. const int64_t n_seqs = ubatch.n_seqs;
  1182. const auto kv_head = kv_state->get_head();
  1183. return ggml_cpy(
  1184. ctx0,
  1185. ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * token_shift_count, 0),
  1186. ggml_view_1d(ctx0, kv_state->get_k_l(il), hparams.n_embd_k_s()*n_seqs, hparams.n_embd_k_s()*kv_head*ggml_element_size(kv_state->get_k_l(il)))
  1187. );
  1188. }
  1189. void llm_graph_context::build_pooling(
  1190. ggml_cgraph * gf,
  1191. ggml_tensor * cls,
  1192. ggml_tensor * cls_b,
  1193. ggml_tensor * cls_out,
  1194. ggml_tensor * cls_out_b) const {
  1195. if (!cparams.embeddings) {
  1196. return;
  1197. }
  1198. ggml_tensor * inp = res->t_embd;
  1199. //// find result_norm tensor for input
  1200. //for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  1201. // inp = ggml_graph_node(gf, i);
  1202. // if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  1203. // break;
  1204. // }
  1205. // inp = nullptr;
  1206. //}
  1207. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  1208. ggml_tensor * cur;
  1209. switch (pooling_type) {
  1210. case LLAMA_POOLING_TYPE_NONE:
  1211. {
  1212. cur = inp;
  1213. } break;
  1214. case LLAMA_POOLING_TYPE_MEAN:
  1215. {
  1216. ggml_tensor * inp_mean = build_inp_mean();
  1217. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  1218. } break;
  1219. case LLAMA_POOLING_TYPE_CLS:
  1220. case LLAMA_POOLING_TYPE_LAST:
  1221. {
  1222. ggml_tensor * inp_cls = build_inp_cls();
  1223. cur = ggml_get_rows(ctx0, inp, inp_cls);
  1224. } break;
  1225. case LLAMA_POOLING_TYPE_RANK:
  1226. {
  1227. ggml_tensor * inp_cls = build_inp_cls();
  1228. inp = ggml_get_rows(ctx0, inp, inp_cls);
  1229. if (cls != nullptr && cls_b != nullptr) {
  1230. // classification head
  1231. // https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566
  1232. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, cls, inp), cls_b);
  1233. cur = ggml_tanh(ctx0, cur);
  1234. // some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en
  1235. // https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896
  1236. if (cls_out) {
  1237. GGML_ASSERT(cls_out_b != nullptr);
  1238. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, cls_out, cur), cls_out_b);
  1239. }
  1240. } else if (cls_out) {
  1241. // Single layer classification head (direct projection)
  1242. // https://github.com/huggingface/transformers/blob/f4fc42216cd56ab6b68270bf80d811614d8d59e4/src/transformers/models/bert/modeling_bert.py#L1476
  1243. GGML_ASSERT(cls_out_b != nullptr);
  1244. cur = ggml_add(ctx0, ggml_mul_mat(ctx0, cls_out, inp), cls_out_b);
  1245. } else {
  1246. GGML_ABORT("RANK pooling requires either cls+cls_b or cls_out+cls_out_b");
  1247. }
  1248. } break;
  1249. default:
  1250. {
  1251. GGML_ABORT("unknown pooling type");
  1252. }
  1253. }
  1254. cb(cur, "result_embd_pooled", -1);
  1255. res->t_embd_pooled = cur;
  1256. ggml_build_forward_expand(gf, cur);
  1257. }
  1258. int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  1259. // TODO move to hparams if a T5 variant appears that uses a different value
  1260. const int64_t max_distance = 128;
  1261. if (bidirectional) {
  1262. n_buckets >>= 1;
  1263. }
  1264. const int64_t max_exact = n_buckets >> 1;
  1265. int32_t relative_position = x - y;
  1266. int32_t relative_bucket = 0;
  1267. if (bidirectional) {
  1268. relative_bucket += (relative_position > 0) * n_buckets;
  1269. relative_position = abs(relative_position);
  1270. } else {
  1271. relative_position = -std::min<int32_t>(relative_position, 0);
  1272. }
  1273. 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));
  1274. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  1275. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  1276. return relative_bucket;
  1277. }