llama-graph.cpp 55 KB

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