llama-graph.cpp 62 KB

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