/src/llama.cpp/src/llama-graph.cpp
Line | Count | Source |
1 | | #include "llama-graph.h" |
2 | | |
3 | | #include "llama-impl.h" |
4 | | #include "llama-batch.h" |
5 | | #include "llama-cparams.h" |
6 | | |
7 | | #include "llama-kv-cache.h" |
8 | | #include "llama-kv-cache-iswa.h" |
9 | | #include "llama-memory-hybrid.h" |
10 | | #include "llama-memory-hybrid-iswa.h" |
11 | | #include "llama-memory-recurrent.h" |
12 | | |
13 | | #include <cassert> |
14 | | #include <cmath> |
15 | | #include <cstring> |
16 | | #include <numeric> |
17 | | #include <sstream> |
18 | | #include <unordered_set> |
19 | | |
20 | | // dedup helpers |
21 | | |
22 | | static ggml_tensor * build_attn_inp_kq_mask( |
23 | | ggml_context * ctx, |
24 | | const llama_kv_cache_context * mctx, |
25 | | const llama_ubatch & ubatch, |
26 | 0 | const llama_cparams & cparams) { |
27 | 0 | const auto n_kv = mctx->get_n_kv(); |
28 | 0 | const auto n_tokens = ubatch.n_tokens; |
29 | 0 | const auto n_stream = cparams.kv_unified ? 1 : ubatch.n_seqs_unq; |
30 | |
|
31 | 0 | ggml_tensor * res = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, n_kv, n_tokens/n_stream, 1, n_stream); |
32 | 0 | ggml_set_input(res); |
33 | 0 | ggml_set_name(res, "attn_inp_kq_mask"); |
34 | |
|
35 | 0 | return res; |
36 | 0 | } |
37 | | |
38 | | static bool can_reuse_kq_mask( |
39 | | ggml_tensor * kq_mask, |
40 | | const llama_kv_cache_context * mctx, |
41 | | const llama_ubatch & ubatch, |
42 | 0 | const llama_cparams & cparams) { |
43 | 0 | const auto n_kv = mctx->get_n_kv(); |
44 | 0 | const auto n_tokens = ubatch.n_tokens; |
45 | 0 | const auto n_stream = cparams.kv_unified ? 1 : ubatch.n_seqs_unq; |
46 | |
|
47 | 0 | bool res = true; |
48 | |
|
49 | 0 | res &= (kq_mask->ne[0] == n_kv); |
50 | 0 | res &= (kq_mask->ne[1] == n_tokens/n_stream); |
51 | 0 | res &= (kq_mask->ne[2] == 1); |
52 | 0 | res &= (kq_mask->ne[3] == n_stream); |
53 | |
|
54 | 0 | return res; |
55 | 0 | } |
56 | | |
57 | | // impl |
58 | | |
59 | | static ggml_tensor * ggml_mul_mat_aux( |
60 | | ggml_context * ctx, |
61 | | ggml_tensor * cur, |
62 | 0 | ggml_tensor * rot) { |
63 | 0 | const auto n = rot->ne[0]; |
64 | |
|
65 | 0 | ggml_tensor * res; |
66 | |
|
67 | 0 | res = ggml_reshape_2d(ctx, cur, n, ggml_nelements(cur)/n); |
68 | 0 | res = ggml_mul_mat (ctx, rot, res); |
69 | 0 | res = ggml_reshape_4d(ctx, res, cur->ne[0], cur->ne[1], cur->ne[2], cur->ne[3]); |
70 | |
|
71 | 0 | return res; |
72 | 0 | } |
73 | | |
74 | 0 | void llm_graph_input_embd::set_input(const llama_ubatch * ubatch) { |
75 | 0 | if (ubatch->token) { |
76 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
77 | |
|
78 | 0 | ggml_backend_tensor_set(tokens, ubatch->token, 0, n_tokens*ggml_element_size(tokens)); |
79 | 0 | } |
80 | |
|
81 | 0 | if (ubatch->embd) { |
82 | 0 | GGML_ASSERT(n_embd == embd->ne[0]); |
83 | |
|
84 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
85 | |
|
86 | 0 | ggml_backend_tensor_set(embd, ubatch->embd, 0, n_tokens*n_embd*ggml_element_size(embd)); |
87 | 0 | } |
88 | 0 | } |
89 | | |
90 | 0 | bool llm_graph_input_embd::can_reuse(const llm_graph_params & params) { |
91 | 0 | bool res = true; |
92 | |
|
93 | 0 | res &= (!params.ubatch.token) || (tokens && tokens->ne[0] == params.ubatch.n_tokens); |
94 | 0 | res &= (!params.ubatch.embd) || (embd && embd->ne[1] == params.ubatch.n_tokens); |
95 | |
|
96 | 0 | return res; |
97 | 0 | } |
98 | | |
99 | 0 | void llm_graph_input_pos::set_input(const llama_ubatch * ubatch) { |
100 | 0 | if (ubatch->pos && pos) { |
101 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
102 | |
|
103 | 0 | if (ubatch->token && n_pos_per_embd == 4) { |
104 | | // in case we're using M-RoPE with text tokens, convert the 1D positions to 4D |
105 | | // the 3 first dims are the same, and 4th dim is all 0 |
106 | 0 | std::vector<llama_pos> pos_data(n_tokens*n_pos_per_embd); |
107 | | // copy the first dimension |
108 | 0 | for (int i = 0; i < n_tokens; ++i) { |
109 | 0 | pos_data[ i] = ubatch->pos[i]; |
110 | 0 | pos_data[ n_tokens + i] = ubatch->pos[i]; |
111 | 0 | pos_data[2 * n_tokens + i] = ubatch->pos[i]; |
112 | 0 | pos_data[3 * n_tokens + i] = 0; // 4th dim is 0 |
113 | 0 | } |
114 | 0 | ggml_backend_tensor_set(pos, pos_data.data(), 0, pos_data.size()*ggml_element_size(pos)); |
115 | 0 | } else { |
116 | 0 | ggml_backend_tensor_set(pos, ubatch->pos, 0, n_tokens*n_pos_per_embd*ggml_element_size(pos)); |
117 | 0 | } |
118 | 0 | } |
119 | 0 | } |
120 | | |
121 | 0 | bool llm_graph_input_pos::can_reuse(const llm_graph_params & params) { |
122 | 0 | bool res = true; |
123 | |
|
124 | 0 | res &= pos->ne[0] == params.ubatch.n_tokens*n_pos_per_embd; |
125 | |
|
126 | 0 | return res; |
127 | 0 | } |
128 | | |
129 | 0 | void llm_graph_input_attn_temp::set_input(const llama_ubatch * ubatch) { |
130 | 0 | if (ubatch->pos && attn_scale) { |
131 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
132 | |
|
133 | 0 | GGML_ASSERT(f_attn_temp_scale != 0.0f); |
134 | 0 | GGML_ASSERT(n_attn_temp_floor_scale != 0); |
135 | |
|
136 | 0 | std::vector<float> attn_scale_data(n_tokens, 0.0f); |
137 | 0 | for (int i = 0; i < n_tokens; ++i) { |
138 | 0 | const float pos = ubatch->pos[i]; |
139 | 0 | attn_scale_data[i] = std::log( |
140 | 0 | std::floor((pos + f_attn_temp_offset) / n_attn_temp_floor_scale) + 1.0 |
141 | 0 | ) * f_attn_temp_scale + 1.0; |
142 | 0 | } |
143 | |
|
144 | 0 | ggml_backend_tensor_set(attn_scale, attn_scale_data.data(), 0, n_tokens*ggml_element_size(attn_scale)); |
145 | 0 | } |
146 | 0 | } |
147 | | |
148 | 0 | void llm_graph_input_pos_bucket::set_input(const llama_ubatch * ubatch) { |
149 | 0 | if (pos_bucket) { |
150 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
151 | |
|
152 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(pos_bucket->buffer)); |
153 | 0 | GGML_ASSERT(!ubatch->equal_seqs()); // TODO: use ubatch->n_seqs instead of failing |
154 | |
|
155 | 0 | int32_t * data = (int32_t *) pos_bucket->data; |
156 | |
|
157 | 0 | for (int j = 0; j < n_tokens; ++j) { |
158 | 0 | for (int i = 0; i < n_tokens; ++i) { |
159 | 0 | data[j*n_tokens + i] = llama_relative_position_bucket(ubatch->pos[i], ubatch->pos[j], hparams.n_rel_attn_bkts, true); |
160 | 0 | } |
161 | 0 | } |
162 | 0 | } |
163 | 0 | } |
164 | | |
165 | 0 | void llm_graph_input_pos_bucket_kv::set_input(const llama_ubatch * ubatch) { |
166 | 0 | if (pos_bucket) { |
167 | 0 | mctx->set_input_pos_bucket(pos_bucket, ubatch); |
168 | 0 | } |
169 | 0 | } |
170 | | |
171 | 0 | void llm_graph_input_out_ids::set_input(const llama_ubatch * ubatch) { |
172 | 0 | GGML_ASSERT(out_ids); |
173 | |
|
174 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
175 | |
|
176 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(out_ids->buffer)); |
177 | 0 | int32_t * data = (int32_t *) out_ids->data; |
178 | |
|
179 | 0 | if (n_outputs == n_tokens) { |
180 | 0 | for (int i = 0; i < n_tokens; ++i) { |
181 | 0 | data[i] = i; |
182 | 0 | } |
183 | |
|
184 | 0 | return; |
185 | 0 | } |
186 | | |
187 | 0 | GGML_ASSERT(ubatch->output); |
188 | |
|
189 | 0 | int n_outputs = 0; |
190 | |
|
191 | 0 | for (int i = 0; i < n_tokens; ++i) { |
192 | 0 | if (ubatch->output[i]) { |
193 | 0 | data[n_outputs++] = i; |
194 | 0 | } |
195 | 0 | } |
196 | 0 | } |
197 | | |
198 | 0 | bool llm_graph_input_out_ids::can_reuse(const llm_graph_params & params) { |
199 | 0 | bool res = true; |
200 | |
|
201 | 0 | res &= n_outputs == params.n_outputs; |
202 | |
|
203 | 0 | return res; |
204 | 0 | } |
205 | | |
206 | 0 | void llm_graph_input_mean::set_input(const llama_ubatch * ubatch) { |
207 | 0 | if (cparams.embeddings && |
208 | 0 | (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN || |
209 | 0 | cparams.pooling_type == LLAMA_POOLING_TYPE_RANK )) { |
210 | |
|
211 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
212 | 0 | const int64_t n_seq_tokens = ubatch->n_seq_tokens; |
213 | 0 | const int64_t n_seqs_unq = ubatch->n_seqs_unq; |
214 | |
|
215 | 0 | GGML_ASSERT(mean); |
216 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(mean->buffer)); |
217 | |
|
218 | 0 | float * data = (float *) mean->data; |
219 | 0 | memset(mean->data, 0, n_tokens*n_seqs_unq*ggml_element_size(mean)); |
220 | |
|
221 | 0 | std::vector<uint64_t> sums(n_seqs_unq, 0); |
222 | 0 | for (int i = 0; i < n_tokens; i += n_seq_tokens) { |
223 | 0 | for (int s = 0; s < ubatch->n_seq_id[i]; ++s) { |
224 | 0 | const llama_seq_id seq_id = ubatch->seq_id[i][s]; |
225 | 0 | const int32_t seq_idx = ubatch->seq_idx[seq_id]; |
226 | |
|
227 | 0 | sums[seq_idx] += ubatch->n_seq_tokens; |
228 | 0 | } |
229 | 0 | } |
230 | |
|
231 | 0 | std::vector<float> div(n_seqs_unq, 0.0f); |
232 | 0 | for (int s = 0; s < n_seqs_unq; ++s) { |
233 | 0 | const uint64_t sum = sums[s]; |
234 | 0 | if (sum > 0) { |
235 | 0 | div[s] = 1.0f/float(sum); |
236 | 0 | } |
237 | 0 | } |
238 | |
|
239 | 0 | for (int i = 0; i < n_tokens; i += n_seq_tokens) { |
240 | 0 | for (int s = 0; s < ubatch->n_seq_id[i]; ++s) { |
241 | 0 | const llama_seq_id seq_id = ubatch->seq_id[i][s]; |
242 | 0 | const int32_t seq_idx = ubatch->seq_idx[seq_id]; |
243 | |
|
244 | 0 | for (int j = 0; j < n_seq_tokens; ++j) { |
245 | 0 | data[seq_idx*n_tokens + i + j] = div[seq_idx]; |
246 | 0 | } |
247 | 0 | } |
248 | 0 | } |
249 | 0 | } |
250 | 0 | } |
251 | | |
252 | 0 | void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) { |
253 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
254 | 0 | const int64_t n_seqs_unq = ubatch->n_seqs_unq; |
255 | |
|
256 | 0 | if (cparams.embeddings && ( |
257 | 0 | cparams.pooling_type == LLAMA_POOLING_TYPE_CLS || |
258 | 0 | cparams.pooling_type == LLAMA_POOLING_TYPE_RANK || |
259 | 0 | cparams.pooling_type == LLAMA_POOLING_TYPE_LAST |
260 | 0 | )) { |
261 | 0 | GGML_ASSERT(cls); |
262 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(cls->buffer)); |
263 | |
|
264 | 0 | uint32_t * data = (uint32_t *) cls->data; |
265 | 0 | memset(cls->data, 0, n_seqs_unq*ggml_element_size(cls)); |
266 | |
|
267 | 0 | std::vector<int> target_pos(n_seqs_unq, -1); |
268 | 0 | std::vector<int> target_row(n_seqs_unq, -1); |
269 | |
|
270 | 0 | const bool last = ( |
271 | 0 | cparams.pooling_type == LLAMA_POOLING_TYPE_LAST || |
272 | 0 | (cparams.pooling_type == LLAMA_POOLING_TYPE_RANK && (arch == LLM_ARCH_QWEN3 || arch == LLM_ARCH_QWEN3VL)) // qwen3 reranking & embedding models use last token |
273 | 0 | ); |
274 | |
|
275 | 0 | for (int i = 0; i < n_tokens; ++i) { |
276 | 0 | const llama_pos pos = ubatch->pos[i]; |
277 | |
|
278 | 0 | for (int s = 0; s < ubatch->n_seq_id[i]; ++s) { |
279 | 0 | const llama_seq_id seq_id = ubatch->seq_id[i][s]; |
280 | 0 | const int32_t seq_idx = ubatch->seq_idx[seq_id]; |
281 | |
|
282 | 0 | if ( |
283 | 0 | (target_pos[seq_idx] == -1) || |
284 | 0 | ( last && pos >= target_pos[seq_idx]) || |
285 | 0 | (!last && pos < target_pos[seq_idx]) |
286 | 0 | ) { |
287 | 0 | target_pos[seq_idx] = pos; |
288 | 0 | target_row[seq_idx] = i; |
289 | 0 | } |
290 | 0 | } |
291 | 0 | } |
292 | |
|
293 | 0 | for (int s = 0; s < n_seqs_unq; ++s) { |
294 | 0 | if (target_row[s] >= 0) { |
295 | 0 | data[s] = target_row[s]; |
296 | 0 | } |
297 | 0 | } |
298 | 0 | } |
299 | 0 | } |
300 | | |
301 | 0 | void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) { |
302 | 0 | GGML_UNUSED(ubatch); |
303 | |
|
304 | 0 | const int64_t n_rs = mctx->get_n_rs(); |
305 | |
|
306 | 0 | if (s_copy) { |
307 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(s_copy->buffer)); |
308 | 0 | int32_t * data = (int32_t *) s_copy->data; |
309 | | |
310 | | // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n |
311 | 0 | for (uint32_t i = 0; i < n_rs; ++i) { |
312 | 0 | data[i] = mctx->s_copy(i); |
313 | 0 | } |
314 | 0 | } |
315 | 0 | } |
316 | | |
317 | 0 | bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) { |
318 | 0 | const auto * mctx = static_cast<const llama_memory_recurrent_context *>(params.mctx); |
319 | |
|
320 | 0 | this->mctx = mctx; |
321 | |
|
322 | 0 | bool res = true; |
323 | |
|
324 | 0 | res &= s_copy->ne[0] == mctx->get_n_rs(); |
325 | |
|
326 | 0 | res &= s_copy_main->ne[0] == params.ubatch.n_seqs; |
327 | 0 | res &= s_copy_extra->ne[0] == mctx->get_n_rs() - params.ubatch.n_seqs; |
328 | |
|
329 | 0 | res &= head == mctx->get_head(); |
330 | 0 | res &= rs_z == mctx->get_rs_z(); |
331 | |
|
332 | 0 | return res; |
333 | 0 | } |
334 | | |
335 | 0 | void llm_graph_input_cross_embd::set_input(const llama_ubatch * ubatch) { |
336 | 0 | GGML_UNUSED(ubatch); |
337 | |
|
338 | 0 | if (cross_embd && !cross->v_embd.empty()) { |
339 | 0 | assert(cross_embd->type == GGML_TYPE_F32); |
340 | |
|
341 | 0 | ggml_backend_tensor_set(cross_embd, cross->v_embd.data(), 0, ggml_nbytes(cross_embd)); |
342 | 0 | } |
343 | 0 | } |
344 | | |
345 | 0 | static void print_mask(const float * data, int64_t n_tokens, int64_t n_kv, int64_t n_swa, llama_swa_type swa_type) { |
346 | 0 | LLAMA_LOG_DEBUG("%s: === Attention mask ===\n", __func__); |
347 | 0 | const char * swa_type_str = "unknown"; |
348 | |
|
349 | 0 | switch (swa_type) { |
350 | 0 | case LLAMA_SWA_TYPE_NONE: swa_type_str = "LLAMA_SWA_TYPE_NONE"; break; |
351 | 0 | case LLAMA_SWA_TYPE_STANDARD: swa_type_str = "LLAMA_SWA_TYPE_STANDARD"; break; |
352 | 0 | case LLAMA_SWA_TYPE_CHUNKED: swa_type_str = "LLAMA_SWA_TYPE_CHUNKED"; break; |
353 | 0 | case LLAMA_SWA_TYPE_SYMMETRIC: swa_type_str = "LLAMA_SWA_TYPE_SYMMETRIC"; break; |
354 | 0 | }; |
355 | |
|
356 | 0 | LLAMA_LOG_DEBUG("%s: n_swa : %d, n_kv: %d, swq_type: %s\n", __func__, (int)n_swa, (int)n_kv, swa_type_str); |
357 | 0 | LLAMA_LOG_DEBUG("%s: '0' = can attend, '∞' = masked\n", __func__); |
358 | 0 | LLAMA_LOG_DEBUG("%s: Rows = query tokens, Columns = key/value tokens\n\n", __func__); |
359 | |
|
360 | 0 | LLAMA_LOG_DEBUG(" "); |
361 | 0 | for (int j = 0; j < std::min((int64_t)20, n_kv); ++j) { |
362 | 0 | LLAMA_LOG_DEBUG("%2d", j); |
363 | 0 | } |
364 | 0 | LLAMA_LOG_DEBUG("\n"); |
365 | |
|
366 | 0 | for (int i = 0; i < std::min((int64_t)20, n_tokens); ++i) { |
367 | 0 | LLAMA_LOG_DEBUG(" %2d ", i); |
368 | 0 | for (int j = 0; j < std::min((int64_t)20, n_kv); ++j) { |
369 | 0 | float val = data[i * n_kv + j]; |
370 | 0 | if (val == -INFINITY) { |
371 | 0 | LLAMA_LOG_DEBUG(" ∞"); |
372 | 0 | } else { |
373 | 0 | LLAMA_LOG_DEBUG(" 0"); |
374 | 0 | } |
375 | 0 | } |
376 | 0 | LLAMA_LOG_DEBUG("\n"); |
377 | 0 | } |
378 | 0 | } |
379 | | |
380 | 0 | void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) { |
381 | 0 | const int64_t n_kv = ubatch->n_tokens; |
382 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
383 | |
|
384 | 0 | const auto fill_mask = [&](float * data, int n_swa, llama_swa_type swa_type) { |
385 | 0 | for (int i1 = 0; i1 < n_tokens; ++i1) { |
386 | 0 | const llama_seq_id s1 = ubatch->seq_id[i1][0]; |
387 | 0 | const llama_pos p1 = ubatch->pos[i1]; |
388 | |
|
389 | 0 | const uint64_t idst = i1*n_kv; |
390 | |
|
391 | 0 | for (int i0 = 0; i0 < n_tokens; ++i0) { |
392 | 0 | const llama_seq_id s0 = ubatch->seq_id[i0][0]; |
393 | 0 | const llama_pos p0 = ubatch->pos[i0]; |
394 | | |
395 | | // mask different sequences |
396 | 0 | if (s0 != s1) { |
397 | 0 | continue; |
398 | 0 | } |
399 | | |
400 | | // mask future tokens |
401 | 0 | if (cparams.causal_attn && p0 > p1) { |
402 | 0 | continue; |
403 | 0 | } |
404 | | |
405 | | // apply SWA if any |
406 | 0 | if (llama_hparams::is_masked_swa(n_swa, swa_type, p0, p1)) { |
407 | 0 | continue; |
408 | 0 | } |
409 | | |
410 | 0 | data[idst + i0] = hparams.use_alibi ? -std::abs(p0 - p1) : 0.0f; |
411 | 0 | } |
412 | 0 | } |
413 | 0 | }; |
414 | |
|
415 | 0 | { |
416 | 0 | GGML_ASSERT(self_kq_mask); |
417 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(self_kq_mask->buffer)); |
418 | |
|
419 | 0 | float * data = (float *) self_kq_mask->data; |
420 | |
|
421 | 0 | std::fill(data, data + ggml_nelements(self_kq_mask), -INFINITY); |
422 | |
|
423 | 0 | fill_mask(data, 0, LLAMA_SWA_TYPE_NONE); |
424 | |
|
425 | 0 | if (debug) { |
426 | 0 | print_mask(data, n_tokens, n_kv, 0, LLAMA_SWA_TYPE_NONE); |
427 | 0 | } |
428 | 0 | } |
429 | |
|
430 | 0 | if (hparams.swa_type != LLAMA_SWA_TYPE_NONE) { |
431 | 0 | GGML_ASSERT(self_kq_mask_swa); |
432 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(self_kq_mask_swa->buffer)); |
433 | |
|
434 | 0 | float * data = (float *) self_kq_mask_swa->data; |
435 | |
|
436 | 0 | std::fill(data, data + ggml_nelements(self_kq_mask_swa), -INFINITY); |
437 | |
|
438 | 0 | fill_mask(data, hparams.n_swa, hparams.swa_type); |
439 | |
|
440 | 0 | if (debug) { |
441 | 0 | print_mask(data, n_tokens, n_kv, hparams.n_swa, hparams.swa_type); |
442 | 0 | } |
443 | 0 | } |
444 | 0 | } |
445 | | |
446 | 0 | void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { |
447 | 0 | mctx->set_input_k_idxs(self_k_idxs, ubatch); |
448 | 0 | mctx->set_input_v_idxs(self_v_idxs, ubatch); |
449 | |
|
450 | 0 | mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); |
451 | |
|
452 | 0 | if (self_k_rot) { |
453 | 0 | mctx->set_input_k_rot(self_k_rot); |
454 | 0 | } |
455 | |
|
456 | 0 | if (self_v_rot) { |
457 | 0 | mctx->set_input_v_rot(self_v_rot); |
458 | 0 | } |
459 | 0 | } |
460 | | |
461 | 0 | bool llm_graph_input_attn_kv::can_reuse(const llm_graph_params & params) { |
462 | 0 | const auto * mctx = static_cast<const llama_kv_cache_context *>(params.mctx); |
463 | |
|
464 | 0 | this->mctx = mctx; |
465 | |
|
466 | 0 | bool res = true; |
467 | |
|
468 | 0 | res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; |
469 | | //res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there |
470 | |
|
471 | 0 | res &= can_reuse_kq_mask(self_kq_mask, mctx, params.ubatch, params.cparams); |
472 | |
|
473 | 0 | return res; |
474 | 0 | } |
475 | | |
476 | 0 | void llm_graph_input_attn_k::set_input(const llama_ubatch * ubatch) { |
477 | 0 | mctx->set_input_k_idxs(self_k_idxs, ubatch); |
478 | |
|
479 | 0 | mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); |
480 | 0 | } |
481 | | |
482 | 0 | bool llm_graph_input_attn_k::can_reuse(const llm_graph_params & params) { |
483 | 0 | const auto * mctx = static_cast<const llama_kv_cache_context *>(params.mctx); |
484 | |
|
485 | 0 | this->mctx = mctx; |
486 | |
|
487 | 0 | bool res = true; |
488 | |
|
489 | 0 | res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; |
490 | |
|
491 | 0 | res &= can_reuse_kq_mask(self_kq_mask, mctx, params.ubatch, params.cparams); |
492 | |
|
493 | 0 | return res; |
494 | 0 | } |
495 | | |
496 | 0 | void llm_graph_input_attn_kv_iswa::set_input(const llama_ubatch * ubatch) { |
497 | 0 | mctx->get_base()->set_input_k_idxs(self_k_idxs, ubatch); |
498 | 0 | mctx->get_base()->set_input_v_idxs(self_v_idxs, ubatch); |
499 | |
|
500 | 0 | mctx->get_base()->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); |
501 | |
|
502 | 0 | mctx->get_swa()->set_input_k_idxs(self_k_idxs_swa, ubatch); |
503 | 0 | mctx->get_swa()->set_input_v_idxs(self_v_idxs_swa, ubatch); |
504 | |
|
505 | 0 | mctx->get_swa()->set_input_kq_mask(self_kq_mask_swa, ubatch, cparams.causal_attn); |
506 | |
|
507 | 0 | if (self_k_rot) { |
508 | 0 | mctx->get_base()->set_input_k_rot(self_k_rot); |
509 | 0 | } |
510 | |
|
511 | 0 | if (self_v_rot) { |
512 | 0 | mctx->get_base()->set_input_v_rot(self_v_rot); |
513 | 0 | } |
514 | |
|
515 | 0 | if (self_k_rot_swa) { |
516 | 0 | mctx->get_swa()->set_input_k_rot(self_k_rot_swa); |
517 | 0 | } |
518 | |
|
519 | 0 | if (self_v_rot_swa) { |
520 | 0 | mctx->get_swa()->set_input_v_rot(self_v_rot_swa); |
521 | 0 | } |
522 | 0 | } |
523 | | |
524 | 0 | bool llm_graph_input_attn_kv_iswa::can_reuse(const llm_graph_params & params) { |
525 | 0 | const auto * mctx = static_cast<const llama_kv_cache_iswa_context *>(params.mctx); |
526 | |
|
527 | 0 | this->mctx = mctx; |
528 | |
|
529 | 0 | bool res = true; |
530 | |
|
531 | 0 | res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; |
532 | | //res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there |
533 | |
|
534 | 0 | res &= self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; |
535 | | //res &= self_v_idxs_swa->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there |
536 | |
|
537 | 0 | res &= can_reuse_kq_mask(self_kq_mask, mctx->get_base(), params.ubatch, params.cparams); |
538 | 0 | res &= can_reuse_kq_mask(self_kq_mask_swa, mctx->get_swa(), params.ubatch, params.cparams); |
539 | |
|
540 | 0 | return res; |
541 | 0 | } |
542 | | |
543 | 0 | void llm_graph_input_attn_cross::set_input(const llama_ubatch * ubatch) { |
544 | 0 | GGML_ASSERT(cross_kq_mask); |
545 | |
|
546 | 0 | const int64_t n_enc = cross_kq_mask->ne[0]; |
547 | 0 | const int64_t n_tokens = ubatch->n_tokens; |
548 | |
|
549 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(cross_kq_mask->buffer)); |
550 | 0 | GGML_ASSERT(!ubatch->equal_seqs()); // TODO: use ubatch->n_seqs instead of failing |
551 | |
|
552 | 0 | float * data = (float *) cross_kq_mask->data; |
553 | |
|
554 | 0 | for (int i = 0; i < n_tokens; ++i) { |
555 | 0 | GGML_ASSERT(!cross->seq_ids_enc.empty() && "llama_encode must be called first"); |
556 | 0 | for (int j = 0; j < n_enc; ++j) { |
557 | 0 | float f = -INFINITY; |
558 | |
|
559 | 0 | for (int s = 0; s < ubatch->n_seq_id[i]; ++s) { |
560 | 0 | const llama_seq_id seq_id = ubatch->seq_id[i][s]; |
561 | |
|
562 | 0 | if (cross->seq_ids_enc[j].find(seq_id) != cross->seq_ids_enc[j].end()) { |
563 | 0 | f = 0.0f; |
564 | 0 | } |
565 | 0 | } |
566 | |
|
567 | 0 | data[i*n_enc + j] = f; |
568 | 0 | } |
569 | 0 | } |
570 | 0 | } |
571 | | |
572 | 0 | void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { |
573 | 0 | mctx->get_attn()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); |
574 | 0 | mctx->get_attn()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); |
575 | |
|
576 | 0 | mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); |
577 | |
|
578 | 0 | if (inp_attn->self_k_rot) { |
579 | 0 | mctx->get_attn()->set_input_k_rot(inp_attn->self_k_rot); |
580 | 0 | } |
581 | |
|
582 | 0 | if (inp_attn->self_v_rot) { |
583 | 0 | mctx->get_attn()->set_input_v_rot(inp_attn->self_v_rot); |
584 | 0 | } |
585 | |
|
586 | 0 | const int64_t n_rs = mctx->get_recr()->get_n_rs(); |
587 | |
|
588 | 0 | if (inp_rs->s_copy) { |
589 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); |
590 | 0 | int32_t * data = (int32_t *) inp_rs->s_copy->data; |
591 | | |
592 | | // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n |
593 | 0 | for (uint32_t i = 0; i < n_rs; ++i) { |
594 | 0 | data[i] = mctx->get_recr()->s_copy(i); |
595 | 0 | } |
596 | 0 | } |
597 | 0 | } |
598 | | |
599 | 0 | bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) { |
600 | 0 | const auto * mctx = static_cast<const llama_memory_hybrid_context *>(params.mctx); |
601 | |
|
602 | 0 | this->mctx = mctx; |
603 | |
|
604 | 0 | bool res = true; |
605 | |
|
606 | 0 | res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; |
607 | | //res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there |
608 | |
|
609 | 0 | res &= can_reuse_kq_mask(inp_attn->self_kq_mask, mctx->get_attn(), params.ubatch, params.cparams); |
610 | |
|
611 | 0 | res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); |
612 | |
|
613 | 0 | res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; |
614 | 0 | res &= inp_rs->s_copy_extra->ne[0] == mctx->get_recr()->get_n_rs() - params.ubatch.n_seqs; |
615 | |
|
616 | 0 | res &= inp_rs->head == mctx->get_recr()->get_head(); |
617 | 0 | res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); |
618 | |
|
619 | 0 | return res; |
620 | 0 | } |
621 | | |
622 | | // TODO: Hybrid input classes are a bit redundant. |
623 | | // Instead of creating a hybrid input, the graph can simply create 2 separate inputs. |
624 | | // Refactoring is required in the future. |
625 | 0 | void llm_graph_input_mem_hybrid_k::set_input(const llama_ubatch * ubatch) { |
626 | 0 | mctx->get_attn()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); |
627 | |
|
628 | 0 | mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); |
629 | |
|
630 | 0 | const int64_t n_rs = mctx->get_recr()->get_n_rs(); |
631 | |
|
632 | 0 | if (inp_rs->s_copy) { |
633 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); |
634 | 0 | int32_t * data = (int32_t *) inp_rs->s_copy->data; |
635 | | |
636 | | // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n |
637 | 0 | for (uint32_t i = 0; i < n_rs; ++i) { |
638 | 0 | data[i] = mctx->get_recr()->s_copy(i); |
639 | 0 | } |
640 | 0 | } |
641 | 0 | } |
642 | | |
643 | 0 | bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) { |
644 | 0 | const auto * mctx = static_cast<const llama_memory_hybrid_context *>(params.mctx); |
645 | |
|
646 | 0 | this->mctx = mctx; |
647 | |
|
648 | 0 | bool res = true; |
649 | |
|
650 | 0 | res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; |
651 | |
|
652 | 0 | res &= can_reuse_kq_mask(inp_attn->self_kq_mask, mctx->get_attn(), params.ubatch, params.cparams); |
653 | |
|
654 | 0 | res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); |
655 | |
|
656 | 0 | res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; |
657 | 0 | res &= inp_rs->s_copy_extra->ne[0] == mctx->get_recr()->get_n_rs() - params.ubatch.n_seqs; |
658 | |
|
659 | 0 | res &= inp_rs->head == mctx->get_recr()->get_head(); |
660 | 0 | res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); |
661 | |
|
662 | 0 | return res; |
663 | 0 | } |
664 | | |
665 | 0 | void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) { |
666 | 0 | const auto * attn_ctx = mctx->get_attn(); |
667 | | |
668 | | // base tensors may not be allocated if there are no non-SWA attention layers |
669 | 0 | if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { |
670 | 0 | attn_ctx->get_base()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); |
671 | 0 | attn_ctx->get_base()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); |
672 | |
|
673 | 0 | attn_ctx->get_base()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); |
674 | 0 | } |
675 | | |
676 | | // swa tensors may not be allocated if there are no SWA attention layers |
677 | 0 | if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { |
678 | 0 | attn_ctx->get_swa()->set_input_k_idxs(inp_attn->self_k_idxs_swa, ubatch); |
679 | 0 | attn_ctx->get_swa()->set_input_v_idxs(inp_attn->self_v_idxs_swa, ubatch); |
680 | |
|
681 | 0 | attn_ctx->get_swa()->set_input_kq_mask(inp_attn->self_kq_mask_swa, ubatch, cparams.causal_attn); |
682 | 0 | } |
683 | |
|
684 | 0 | if (inp_attn->self_k_rot) { |
685 | 0 | attn_ctx->get_base()->set_input_k_rot(inp_attn->self_k_rot); |
686 | 0 | } |
687 | |
|
688 | 0 | if (inp_attn->self_v_rot) { |
689 | 0 | attn_ctx->get_base()->set_input_v_rot(inp_attn->self_v_rot); |
690 | 0 | } |
691 | |
|
692 | 0 | if (inp_attn->self_k_rot_swa) { |
693 | 0 | attn_ctx->get_swa()->set_input_k_rot(inp_attn->self_k_rot_swa); |
694 | 0 | } |
695 | |
|
696 | 0 | if (inp_attn->self_v_rot_swa) { |
697 | 0 | attn_ctx->get_swa()->set_input_v_rot(inp_attn->self_v_rot_swa); |
698 | 0 | } |
699 | |
|
700 | 0 | const int64_t n_rs = mctx->get_recr()->get_n_rs(); |
701 | |
|
702 | 0 | if (inp_rs->s_copy) { |
703 | 0 | GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); |
704 | 0 | int32_t * data = (int32_t *) inp_rs->s_copy->data; |
705 | | |
706 | | // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n |
707 | 0 | for (uint32_t i = 0; i < n_rs; ++i) { |
708 | 0 | data[i] = mctx->get_recr()->s_copy(i); |
709 | 0 | } |
710 | 0 | } |
711 | 0 | } |
712 | | |
713 | 0 | bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) { |
714 | 0 | const auto * mctx = static_cast<const llama_memory_hybrid_iswa_context *>(params.mctx); |
715 | |
|
716 | 0 | this->mctx = mctx; |
717 | |
|
718 | 0 | bool res = true; |
719 | |
|
720 | 0 | const auto * attn_ctx = mctx->get_attn(); |
721 | | |
722 | | // base tensors may not be allocated if there are no non-SWA attention layers |
723 | 0 | if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { |
724 | 0 | res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; |
725 | | //res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there |
726 | |
|
727 | 0 | res &= can_reuse_kq_mask(inp_attn->self_kq_mask, attn_ctx->get_base(), params.ubatch, params.cparams); |
728 | 0 | } |
729 | | |
730 | | // swa tensors may not be allocated if there are no SWA attention layers |
731 | 0 | if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { |
732 | 0 | res &= inp_attn->self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; |
733 | | //res &= inp_attn->self_v_idxs_swa->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there |
734 | |
|
735 | 0 | res &= can_reuse_kq_mask(inp_attn->self_kq_mask_swa, attn_ctx->get_swa(), params.ubatch, params.cparams); |
736 | 0 | } |
737 | |
|
738 | 0 | res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); |
739 | |
|
740 | 0 | res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; |
741 | 0 | res &= inp_rs->s_copy_extra->ne[0] == mctx->get_recr()->get_n_rs() - params.ubatch.n_seqs; |
742 | |
|
743 | 0 | res &= inp_rs->head == mctx->get_recr()->get_head(); |
744 | 0 | res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); |
745 | |
|
746 | 0 | return res; |
747 | 0 | } |
748 | | |
749 | 0 | void llm_graph_input_sampling::set_input(const llama_ubatch * ubatch) { |
750 | | // set the inputs only for the active samplers in the current ubatch |
751 | 0 | std::unordered_set<llama_seq_id> active_samplers; |
752 | 0 | for (uint32_t i = 0; i < ubatch->n_tokens; i++) { |
753 | 0 | if (ubatch->output[i]) { |
754 | 0 | llama_seq_id seq_id = ubatch->seq_id[i][0]; |
755 | 0 | active_samplers.insert(seq_id); |
756 | 0 | } |
757 | 0 | } |
758 | |
|
759 | 0 | for (auto seq_id : active_samplers) { |
760 | 0 | if (samplers.find(seq_id) == samplers.end()) { |
761 | 0 | continue; |
762 | 0 | } |
763 | | |
764 | 0 | auto & sampler = samplers[seq_id]; |
765 | |
|
766 | 0 | if (sampler->iface->backend_set_input) { |
767 | 0 | sampler->iface->backend_set_input(sampler); |
768 | 0 | } |
769 | 0 | } |
770 | 0 | } |
771 | | |
772 | 0 | bool llm_graph_input_sampling::can_reuse(const llm_graph_params & params) { |
773 | 0 | if (samplers.size() != params.samplers.size()) { |
774 | 0 | return false; |
775 | 0 | } |
776 | | |
777 | 0 | for (const auto & [seq_id, sampler] : params.samplers) { |
778 | 0 | if (samplers[seq_id] != sampler) { |
779 | 0 | return false; |
780 | 0 | } |
781 | 0 | } |
782 | | |
783 | 0 | return true; |
784 | 0 | } |
785 | | |
786 | | // |
787 | | // llm_graph_result |
788 | | // |
789 | | |
790 | 0 | llm_graph_result::llm_graph_result(int64_t max_nodes) : max_nodes(max_nodes) { |
791 | 0 | reset(); |
792 | |
|
793 | 0 | const char * LLAMA_GRAPH_RESULT_DEBUG = getenv("LLAMA_GRAPH_RESULT_DEBUG"); |
794 | 0 | debug = LLAMA_GRAPH_RESULT_DEBUG ? atoi(LLAMA_GRAPH_RESULT_DEBUG) : 0; |
795 | 0 | } |
796 | | |
797 | 0 | int64_t llm_graph_result::get_max_nodes() const { |
798 | 0 | return max_nodes; |
799 | 0 | } |
800 | | |
801 | 0 | void llm_graph_result::reset() { |
802 | 0 | t_inp_tokens = nullptr; |
803 | 0 | t_inp_embd = nullptr; |
804 | 0 | t_logits = nullptr; |
805 | 0 | t_embd = nullptr; |
806 | 0 | t_embd_pooled = nullptr; |
807 | 0 | t_sampled.clear(); |
808 | 0 | t_sampled_probs.clear(); |
809 | 0 | t_sampled_logits.clear(); |
810 | 0 | t_candidates.clear(); |
811 | |
|
812 | 0 | params = {}; |
813 | |
|
814 | 0 | inputs.clear(); |
815 | |
|
816 | 0 | buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false)); |
817 | |
|
818 | 0 | ggml_init_params params = { |
819 | 0 | /*.mem_size =*/ buf_compute_meta.size(), |
820 | 0 | /*.mem_buffer =*/ buf_compute_meta.data(), |
821 | 0 | /*.no_alloc =*/ true, |
822 | 0 | }; |
823 | |
|
824 | 0 | ctx_compute.reset(ggml_init(params)); |
825 | |
|
826 | 0 | gf = ggml_new_graph_custom(ctx_compute.get(), max_nodes, false); |
827 | 0 | } |
828 | | |
829 | 0 | void llm_graph_result::set_inputs(const llama_ubatch * ubatch) { |
830 | 0 | for (auto & input : inputs) { |
831 | 0 | input->set_input(ubatch); |
832 | 0 | } |
833 | 0 | } |
834 | | |
835 | 0 | void llm_graph_result::set_outputs() { |
836 | 0 | if (t_logits != nullptr) { |
837 | 0 | ggml_set_output(t_logits); |
838 | 0 | } |
839 | 0 | if (t_embd != nullptr) { |
840 | 0 | ggml_set_output(t_embd); |
841 | 0 | } |
842 | 0 | if (t_embd_pooled != nullptr) { |
843 | 0 | ggml_set_output(t_embd_pooled); |
844 | 0 | } |
845 | 0 | for (auto & [seq_id, t] : t_sampled) { |
846 | 0 | if (t != nullptr) { |
847 | 0 | ggml_set_output(t); |
848 | 0 | } |
849 | 0 | } |
850 | 0 | for (auto & [seq_id, t] : t_sampled_probs) { |
851 | 0 | if (t != nullptr) { |
852 | 0 | ggml_set_output(t); |
853 | 0 | } |
854 | 0 | } |
855 | 0 | for (auto & [seq_id, t] : t_sampled_logits) { |
856 | 0 | if (t != nullptr) { |
857 | 0 | ggml_set_output(t); |
858 | 0 | } |
859 | 0 | } |
860 | 0 | for (auto & [seq_id, t] : t_candidates) { |
861 | 0 | if (t != nullptr) { |
862 | 0 | ggml_set_output(t); |
863 | 0 | } |
864 | 0 | } |
865 | 0 | } |
866 | | |
867 | 0 | bool llm_graph_result::can_reuse(const llm_graph_params & params) { |
868 | 0 | if (!this->params.allow_reuse(params)) { |
869 | 0 | if (debug > 1) { |
870 | 0 | LLAMA_LOG_DEBUG("%s: cannot reuse graph due to incompatible graph parameters\n", __func__); |
871 | 0 | } |
872 | |
|
873 | 0 | return false; |
874 | 0 | } |
875 | | |
876 | 0 | if (debug > 1) { |
877 | 0 | LLAMA_LOG_DEBUG("%s: checking compatibility of %d inputs:\n", __func__, (int) inputs.size()); |
878 | 0 | } |
879 | |
|
880 | 0 | bool res = true; |
881 | |
|
882 | 0 | for (auto & input : inputs) { |
883 | 0 | const bool cur = input->can_reuse(params); |
884 | |
|
885 | 0 | if (debug > 1) { |
886 | 0 | LLAMA_LOG_DEBUG("%s: can_reuse = %d\n", "placeholder", cur); |
887 | 0 | } |
888 | |
|
889 | 0 | res = res && cur; |
890 | 0 | } |
891 | |
|
892 | 0 | if (debug > 0) { |
893 | 0 | LLAMA_LOG_DEBUG("%s: can reuse graph = %d\n", __func__, res); |
894 | 0 | } |
895 | |
|
896 | 0 | return res; |
897 | 0 | } |
898 | | |
899 | 0 | llm_graph_input_i * llm_graph_result::add_input(llm_graph_input_ptr input) { |
900 | 0 | inputs.emplace_back(std::move(input)); |
901 | 0 | return inputs.back().get(); |
902 | 0 | } |
903 | | |
904 | 0 | void llm_graph_result::set_params(const llm_graph_params & params) { |
905 | 0 | this->params = params; |
906 | 0 | } |
907 | | |
908 | | // |
909 | | // llm_graph_context |
910 | | // |
911 | | |
912 | | llm_graph_context::llm_graph_context(const llm_graph_params & params) : |
913 | 0 | arch (params.arch), |
914 | 0 | hparams (params.hparams), |
915 | 0 | cparams (params.cparams), |
916 | 0 | ubatch (params.ubatch), |
917 | 0 | n_embd (hparams.n_embd), |
918 | 0 | n_layer (hparams.n_layer), |
919 | 0 | n_rot (hparams.n_rot()), |
920 | 0 | n_ctx (cparams.n_ctx), |
921 | 0 | n_head (hparams.n_head()), |
922 | 0 | n_head_kv (hparams.n_head_kv()), |
923 | 0 | n_embd_head_k (hparams.n_embd_head_k()), |
924 | 0 | n_embd_k_gqa (hparams.n_embd_k_gqa()), |
925 | 0 | n_embd_head_v (hparams.n_embd_head_v()), |
926 | 0 | n_embd_v_gqa (hparams.n_embd_v_gqa()), |
927 | 0 | n_expert (hparams.n_expert), |
928 | 0 | n_expert_used (cparams.warmup ? hparams.n_expert : hparams.n_expert_used), |
929 | 0 | freq_base (cparams.rope_freq_base), |
930 | 0 | freq_scale (cparams.rope_freq_scale), |
931 | 0 | ext_factor (cparams.yarn_ext_factor), |
932 | 0 | attn_factor (cparams.yarn_attn_factor), |
933 | 0 | beta_fast (cparams.yarn_beta_fast), |
934 | 0 | beta_slow (cparams.yarn_beta_slow), |
935 | 0 | norm_eps (hparams.f_norm_eps), |
936 | 0 | norm_rms_eps (hparams.f_norm_rms_eps), |
937 | 0 | n_tokens (ubatch.n_tokens), |
938 | 0 | n_outputs (params.n_outputs), |
939 | 0 | n_ctx_orig (cparams.n_ctx_orig_yarn), |
940 | 0 | pooling_type (cparams.pooling_type), |
941 | 0 | rope_type (hparams.rope_type), |
942 | 0 | sched (params.sched), |
943 | 0 | backend_cpu (params.backend_cpu), |
944 | 0 | cvec (params.cvec), |
945 | 0 | loras (params.loras), |
946 | 0 | mctx (params.mctx), |
947 | 0 | cross (params.cross), |
948 | 0 | samplers (params.samplers), |
949 | 0 | cb_func (params.cb), |
950 | 0 | res (params.res), |
951 | 0 | ctx0 (res->get_ctx()), |
952 | 0 | gf (res->get_gf()) { |
953 | 0 | res->set_params(params); |
954 | 0 | } |
955 | | |
956 | 0 | void llm_graph_context::cb(ggml_tensor * cur, const char * name, int il) const { |
957 | 0 | if (cb_func) { |
958 | 0 | cb_func(ubatch, cur, name, il); |
959 | 0 | } |
960 | 0 | } |
961 | | |
962 | | ggml_tensor * llm_graph_context::build_cvec( |
963 | | ggml_tensor * cur, |
964 | 0 | int il) const { |
965 | 0 | return cvec->apply_to(ctx0, cur, il); |
966 | 0 | } |
967 | | |
968 | | ggml_tensor * llm_graph_context::build_lora_mm( |
969 | | ggml_tensor * w, |
970 | | ggml_tensor * cur, |
971 | 0 | ggml_tensor * w_s) const { |
972 | 0 | ggml_tensor * res = ggml_mul_mat(ctx0, w, cur); |
973 | |
|
974 | 0 | for (const auto & lora : *loras) { |
975 | 0 | llama_adapter_lora_weight * lw = lora.first->get_weight(w); |
976 | 0 | if (lw == nullptr) { |
977 | 0 | continue; |
978 | 0 | } |
979 | | |
980 | 0 | const float adapter_scale = lora.second; |
981 | 0 | const float scale = lw->get_scale(lora.first->alpha, adapter_scale); |
982 | |
|
983 | 0 | ggml_tensor * ab_cur = ggml_mul_mat( |
984 | 0 | ctx0, lw->b, |
985 | 0 | ggml_mul_mat(ctx0, lw->a, cur) |
986 | 0 | ); |
987 | |
|
988 | 0 | ab_cur = ggml_scale(ctx0, ab_cur, scale); |
989 | 0 | res = ggml_add(ctx0, res, ab_cur); |
990 | 0 | } |
991 | |
|
992 | 0 | if (w_s) { |
993 | 0 | res = ggml_mul(ctx0, res, w_s); |
994 | 0 | } |
995 | |
|
996 | 0 | return res; |
997 | 0 | } |
998 | | |
999 | | ggml_tensor * llm_graph_context::build_lora_mm_id( |
1000 | | ggml_tensor * w, // ggml_tensor * as |
1001 | | ggml_tensor * cur, // ggml_tensor * b |
1002 | 0 | ggml_tensor * ids) const { |
1003 | 0 | ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids); |
1004 | 0 | for (const auto & lora : *loras) { |
1005 | 0 | llama_adapter_lora_weight * lw = lora.first->get_weight(w); |
1006 | 0 | if (lw == nullptr) { |
1007 | 0 | continue; |
1008 | 0 | } |
1009 | | |
1010 | 0 | const float alpha = lora.first->alpha; |
1011 | 0 | const float rank = (float) lw->b->ne[0]; |
1012 | 0 | const float scale = alpha ? lora.second * alpha / rank : lora.second; |
1013 | |
|
1014 | 0 | ggml_tensor * ab_cur = ggml_mul_mat_id( |
1015 | 0 | ctx0, lw->b, |
1016 | 0 | ggml_mul_mat_id(ctx0, lw->a, cur, ids), |
1017 | 0 | ids |
1018 | 0 | ); |
1019 | |
|
1020 | 0 | ab_cur = ggml_scale(ctx0, ab_cur, scale); |
1021 | 0 | res = ggml_add(ctx0, res, ab_cur); |
1022 | 0 | } |
1023 | |
|
1024 | 0 | return res; |
1025 | 0 | } |
1026 | | |
1027 | | ggml_tensor * llm_graph_context::build_norm( |
1028 | | ggml_tensor * cur, |
1029 | | ggml_tensor * mw, |
1030 | | ggml_tensor * mb, |
1031 | | llm_norm_type type, |
1032 | 0 | int il) const { |
1033 | 0 | switch (type) { |
1034 | 0 | case LLM_NORM: cur = ggml_norm (ctx0, cur, hparams.f_norm_eps); break; |
1035 | 0 | case LLM_NORM_RMS: cur = ggml_rms_norm(ctx0, cur, hparams.f_norm_rms_eps); break; |
1036 | 0 | case LLM_NORM_GROUP: |
1037 | 0 | { |
1038 | 0 | cur = ggml_reshape_3d(ctx0, cur, cur->ne[0], 1, cur->ne[1]); |
1039 | 0 | cur = ggml_group_norm(ctx0, cur, hparams.n_norm_groups, hparams.f_norm_group_eps); |
1040 | 0 | cur = ggml_reshape_2d(ctx0, cur, cur->ne[0], cur->ne[2]); |
1041 | 0 | } break; |
1042 | 0 | } |
1043 | | |
1044 | 0 | if (mw || mb) { |
1045 | 0 | cb(cur, "norm", il); |
1046 | 0 | } |
1047 | |
|
1048 | 0 | if (mw) { |
1049 | 0 | cur = ggml_mul(ctx0, cur, mw); |
1050 | 0 | if (mb) { |
1051 | 0 | cb(cur, "norm_w", il); |
1052 | 0 | } |
1053 | 0 | } |
1054 | |
|
1055 | 0 | if (mb) { |
1056 | 0 | cur = ggml_add(ctx0, cur, mb); |
1057 | 0 | } |
1058 | |
|
1059 | 0 | return cur; |
1060 | 0 | } |
1061 | | |
1062 | | ggml_tensor * llm_graph_context::build_ffn( |
1063 | | ggml_tensor * cur, |
1064 | | ggml_tensor * up, |
1065 | | ggml_tensor * up_b, |
1066 | | ggml_tensor * up_s, |
1067 | | ggml_tensor * gate, |
1068 | | ggml_tensor * gate_b, |
1069 | | ggml_tensor * gate_s, |
1070 | | ggml_tensor * down, |
1071 | | ggml_tensor * down_b, |
1072 | | ggml_tensor * down_s, |
1073 | | ggml_tensor * act_scales, |
1074 | | llm_ffn_op_type type_op, |
1075 | | llm_ffn_gate_type type_gate, |
1076 | 0 | int il) const { |
1077 | 0 | ggml_tensor * tmp = up ? build_lora_mm(up, cur) : cur; |
1078 | 0 | cb(tmp, "ffn_up", il); |
1079 | |
|
1080 | 0 | if (up_b) { |
1081 | 0 | tmp = ggml_add(ctx0, tmp, up_b); |
1082 | 0 | cb(tmp, "ffn_up_b", il); |
1083 | 0 | } |
1084 | |
|
1085 | 0 | if (up_s) { |
1086 | 0 | tmp = ggml_mul(ctx0, tmp, up_s); |
1087 | 0 | cb(tmp, "ffn_up_s", il); |
1088 | 0 | } |
1089 | |
|
1090 | 0 | if (gate) { |
1091 | 0 | switch (type_gate) { |
1092 | 0 | case LLM_FFN_SEQ: |
1093 | 0 | { |
1094 | 0 | cur = build_lora_mm(gate, tmp); |
1095 | 0 | cb(cur, "ffn_gate", il); |
1096 | 0 | } break; |
1097 | 0 | case LLM_FFN_PAR: |
1098 | 0 | { |
1099 | 0 | cur = build_lora_mm(gate, cur); |
1100 | 0 | cb(cur, "ffn_gate", il); |
1101 | 0 | } break; |
1102 | 0 | } |
1103 | | |
1104 | 0 | if (gate_b) { |
1105 | 0 | cur = ggml_add(ctx0, cur, gate_b); |
1106 | 0 | cb(cur, "ffn_gate_b", il); |
1107 | 0 | } |
1108 | |
|
1109 | 0 | if (gate_s) { |
1110 | 0 | cur = ggml_mul(ctx0, cur, gate_s); |
1111 | 0 | cb(cur, "ffn_gate_s", il); |
1112 | 0 | } |
1113 | |
|
1114 | 0 | } else { |
1115 | 0 | cur = tmp; |
1116 | 0 | } |
1117 | | |
1118 | 0 | switch (type_op) { |
1119 | 0 | case LLM_FFN_SILU: |
1120 | 0 | if (gate && type_gate == LLM_FFN_PAR) { |
1121 | | // Step35: HF clamps gate (after SiLU) and up before multiplication |
1122 | 0 | if (arch == LLM_ARCH_STEP35 && il >= 0) { |
1123 | 0 | const float limit = hparams.swiglu_clamp_shexp[il]; |
1124 | 0 | constexpr float eps = 1e-6f; |
1125 | 0 | if (limit > eps) { |
1126 | 0 | ggml_tensor * gate_act = ggml_silu(ctx0, cur); |
1127 | 0 | cb(gate_act, "ffn_silu", il); |
1128 | 0 | gate_act = ggml_clamp(ctx0, gate_act, -INFINITY, limit); |
1129 | 0 | cb(gate_act, "ffn_silu_clamped", il); |
1130 | |
|
1131 | 0 | tmp = ggml_clamp(ctx0, tmp, -limit, limit); |
1132 | 0 | cb(tmp, "ffn_up_clamped", il); |
1133 | |
|
1134 | 0 | cur = ggml_mul(ctx0, gate_act, tmp); |
1135 | 0 | cb(cur, "ffn_swiglu_limited", il); |
1136 | 0 | type_gate = LLM_FFN_SEQ; |
1137 | 0 | break; |
1138 | 0 | } |
1139 | 0 | } |
1140 | | |
1141 | 0 | cur = ggml_swiglu_split(ctx0, cur, tmp); |
1142 | 0 | cb(cur, "ffn_swiglu", il); |
1143 | 0 | type_gate = LLM_FFN_SEQ; |
1144 | 0 | } else { |
1145 | 0 | cur = ggml_silu(ctx0, cur); |
1146 | 0 | cb(cur, "ffn_silu", il); |
1147 | 0 | } break; |
1148 | 0 | case LLM_FFN_GELU: |
1149 | 0 | if (gate && type_gate == LLM_FFN_PAR) { |
1150 | 0 | cur = ggml_geglu_split(ctx0, cur, tmp); |
1151 | 0 | cb(cur, "ffn_geglu", il); |
1152 | 0 | type_gate = LLM_FFN_SEQ; |
1153 | 0 | } else { |
1154 | 0 | cur = ggml_gelu(ctx0, cur); |
1155 | 0 | cb(cur, "ffn_gelu", il); |
1156 | 0 | if (act_scales != NULL) { |
1157 | 0 | cur = ggml_div(ctx0, cur, act_scales); |
1158 | 0 | cb(cur, "ffn_act", il); |
1159 | 0 | } |
1160 | 0 | } break; |
1161 | 0 | case LLM_FFN_RELU: |
1162 | 0 | if (gate && type_gate == LLM_FFN_PAR) { |
1163 | 0 | cur = ggml_reglu_split(ctx0, cur, tmp); |
1164 | 0 | cb(cur, "ffn_reglu", il); |
1165 | 0 | type_gate = LLM_FFN_SEQ; |
1166 | 0 | } else { |
1167 | 0 | cur = ggml_relu(ctx0, cur); |
1168 | 0 | cb(cur, "ffn_relu", il); |
1169 | 0 | } break; |
1170 | 0 | case LLM_FFN_RELU_SQR: |
1171 | 0 | { |
1172 | 0 | cur = ggml_relu(ctx0, cur); |
1173 | 0 | cb(cur, "ffn_relu", il); |
1174 | |
|
1175 | 0 | cur = ggml_sqr(ctx0, cur); |
1176 | 0 | cb(cur, "ffn_sqr(relu)", il); |
1177 | 0 | } break; |
1178 | 0 | case LLM_FFN_SWIGLU: |
1179 | 0 | { |
1180 | 0 | cur = ggml_swiglu(ctx0, cur); |
1181 | 0 | cb(cur, "ffn_swiglu", il); |
1182 | 0 | } break; |
1183 | 0 | case LLM_FFN_GEGLU: |
1184 | 0 | { |
1185 | 0 | cur = ggml_geglu(ctx0, cur); |
1186 | 0 | cb(cur, "ffn_geglu", il); |
1187 | 0 | } break; |
1188 | 0 | case LLM_FFN_REGLU: |
1189 | 0 | { |
1190 | 0 | cur = ggml_reglu(ctx0, cur); |
1191 | 0 | cb(cur, "ffn_reglu", il); |
1192 | 0 | } break; |
1193 | 0 | default: |
1194 | 0 | GGML_ABORT("fatal error"); |
1195 | 0 | } |
1196 | | |
1197 | 0 | if (gate && type_gate == LLM_FFN_PAR) { |
1198 | 0 | cur = ggml_mul(ctx0, cur, tmp); |
1199 | 0 | cb(cur, "ffn_gate_par", il); |
1200 | 0 | } |
1201 | |
|
1202 | 0 | if (down) { |
1203 | 0 | cur = build_lora_mm(down, cur); |
1204 | 0 | if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE || arch == LLM_ARCH_JAIS2) { |
1205 | | // GLM4, GLM4_MOE, and JAIS2 seem to have numerical issues with half-precision accumulators |
1206 | 0 | ggml_mul_mat_set_prec(cur, GGML_PREC_F32); |
1207 | 0 | } |
1208 | 0 | } |
1209 | |
|
1210 | 0 | if (down_b) { |
1211 | 0 | cb(cur, "ffn_down", il); |
1212 | 0 | } |
1213 | |
|
1214 | 0 | if (down_b) { |
1215 | 0 | cur = ggml_add(ctx0, cur, down_b); |
1216 | 0 | } |
1217 | |
|
1218 | 0 | if (down_s) { |
1219 | 0 | cur = ggml_mul(ctx0, cur, down_s); |
1220 | 0 | cb(cur, "ffn_down_s", il); |
1221 | 0 | } |
1222 | |
|
1223 | 0 | return cur; |
1224 | 0 | } |
1225 | | |
1226 | | ggml_tensor * llm_graph_context::build_moe_ffn( |
1227 | | ggml_tensor * cur, |
1228 | | ggml_tensor * gate_inp, |
1229 | | ggml_tensor * up_exps, |
1230 | | ggml_tensor * gate_exps, |
1231 | | ggml_tensor * down_exps, |
1232 | | ggml_tensor * exp_probs_b, |
1233 | | int64_t n_expert, |
1234 | | int64_t n_expert_used, |
1235 | | llm_ffn_op_type type_op, |
1236 | | bool norm_w, |
1237 | | float w_scale, |
1238 | | llama_expert_gating_func_type gating_op, |
1239 | | int il, |
1240 | | ggml_tensor * probs_in, |
1241 | | ggml_tensor * gate_up_exps, |
1242 | | ggml_tensor * up_exps_s, |
1243 | | ggml_tensor * gate_exps_s, |
1244 | 0 | ggml_tensor * down_exps_s) const { |
1245 | 0 | return build_moe_ffn( |
1246 | 0 | cur, |
1247 | 0 | gate_inp, /* gate_inp_b */ nullptr, |
1248 | 0 | up_exps, /* up_exps_b */ nullptr, |
1249 | 0 | gate_exps, /* gate_exps_b */ nullptr, |
1250 | 0 | down_exps, /* down_exps_b */ nullptr, |
1251 | 0 | exp_probs_b, |
1252 | 0 | n_expert, |
1253 | 0 | n_expert_used, |
1254 | 0 | type_op, |
1255 | 0 | norm_w, |
1256 | 0 | w_scale, |
1257 | 0 | gating_op, |
1258 | 0 | il, |
1259 | 0 | probs_in, |
1260 | 0 | gate_up_exps, |
1261 | 0 | /* gate_up_exps_b */ nullptr, |
1262 | 0 | up_exps_s, |
1263 | 0 | gate_exps_s, |
1264 | 0 | down_exps_s |
1265 | 0 | ); |
1266 | 0 | } |
1267 | | |
1268 | | ggml_tensor * llm_graph_context::build_moe_ffn( |
1269 | | ggml_tensor * cur, |
1270 | | ggml_tensor * gate_inp, |
1271 | | ggml_tensor * gate_inp_b, |
1272 | | ggml_tensor * up_exps, |
1273 | | ggml_tensor * up_exps_b, |
1274 | | ggml_tensor * gate_exps, |
1275 | | ggml_tensor * gate_exps_b, |
1276 | | ggml_tensor * down_exps, |
1277 | | ggml_tensor * down_exps_b, |
1278 | | ggml_tensor * exp_probs_b, |
1279 | | int64_t n_expert, |
1280 | | int64_t n_expert_used, |
1281 | | llm_ffn_op_type type_op, |
1282 | | bool norm_w, |
1283 | | float w_scale, |
1284 | | llama_expert_gating_func_type gating_op, |
1285 | | int il, |
1286 | | ggml_tensor * probs_in, |
1287 | | ggml_tensor * gate_up_exps, |
1288 | | ggml_tensor * gate_up_exps_b, |
1289 | | ggml_tensor * up_exps_s, |
1290 | | ggml_tensor * gate_exps_s, |
1291 | 0 | ggml_tensor * down_exps_s) const { |
1292 | 0 | const int64_t n_embd = cur->ne[0]; |
1293 | 0 | const int64_t n_tokens = cur->ne[1]; |
1294 | 0 | const bool weight_before_ffn = arch == LLM_ARCH_LLAMA4; // for llama4, we apply the sigmoid-ed weights before the FFN |
1295 | |
|
1296 | 0 | ggml_tensor * logits = nullptr; |
1297 | |
|
1298 | 0 | if (probs_in == nullptr) { |
1299 | 0 | logits = build_lora_mm(gate_inp, cur); // [n_expert, n_tokens] |
1300 | 0 | cb(logits, "ffn_moe_logits", il); |
1301 | 0 | } else { |
1302 | 0 | logits = probs_in; |
1303 | 0 | } |
1304 | |
|
1305 | 0 | if (gate_inp_b) { |
1306 | 0 | logits = ggml_add(ctx0, logits, gate_inp_b); |
1307 | 0 | cb(logits, "ffn_moe_logits_biased", il); |
1308 | 0 | } |
1309 | |
|
1310 | 0 | ggml_tensor * probs = nullptr; |
1311 | 0 | switch (gating_op) { |
1312 | 0 | case LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX: |
1313 | 0 | { |
1314 | 0 | probs = ggml_soft_max(ctx0, logits); // [n_expert, n_tokens] |
1315 | 0 | } break; |
1316 | 0 | case LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID: |
1317 | 0 | { |
1318 | 0 | probs = ggml_sigmoid(ctx0, logits); // [n_expert, n_tokens] |
1319 | 0 | } break; |
1320 | 0 | case LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX_WEIGHT: |
1321 | 0 | { |
1322 | 0 | probs = logits; // [n_expert, n_tokens] |
1323 | 0 | } break; |
1324 | 0 | default: |
1325 | 0 | GGML_ABORT("fatal error"); |
1326 | 0 | } |
1327 | 0 | cb(probs, "ffn_moe_probs", il); |
1328 | | |
1329 | | // add experts selection bias - introduced in DeepSeek V3 |
1330 | | // leave probs unbiased as it's later used to get expert weights |
1331 | 0 | ggml_tensor * selection_probs = probs; |
1332 | 0 | if (exp_probs_b != nullptr) { |
1333 | 0 | selection_probs = ggml_add(ctx0, probs, exp_probs_b); |
1334 | 0 | cb(selection_probs, "ffn_moe_probs_biased", il); |
1335 | 0 | } |
1336 | | |
1337 | | // llama4 doesn't have exp_probs_b, and sigmoid is only used after top_k |
1338 | | // see: https://github.com/meta-llama/llama-models/blob/699a02993512fb36936b1b0741e13c06790bcf98/models/llama4/moe.py#L183-L198 |
1339 | 0 | if (arch == LLM_ARCH_LLAMA4) { |
1340 | 0 | selection_probs = logits; |
1341 | 0 | } |
1342 | |
|
1343 | 0 | if (arch == LLM_ARCH_GROVEMOE) { |
1344 | 0 | selection_probs = ggml_sigmoid(ctx0, logits); // [n_expert, n_tokens] |
1345 | 0 | cb(selection_probs, "ffn_moe_probs_biased", il); |
1346 | 0 | } |
1347 | | |
1348 | | // select top n_group_used expert groups |
1349 | | // https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/e815299b0bcbac849fa540c768ef21845365c9eb/modeling_deepseek.py#L440-L457 |
1350 | 0 | if (hparams.n_expert_groups > 1 && n_tokens > 0) { |
1351 | 0 | const int64_t n_exp_per_group = n_expert / hparams.n_expert_groups; |
1352 | | |
1353 | | // organize experts into n_expert_groups |
1354 | 0 | ggml_tensor * selection_groups = ggml_reshape_3d(ctx0, selection_probs, n_exp_per_group, hparams.n_expert_groups, n_tokens); // [n_exp_per_group, n_expert_groups, n_tokens] |
1355 | |
|
1356 | 0 | ggml_tensor * group_scores = ggml_argsort_top_k(ctx0, selection_groups, 2); // [2, n_expert_groups, n_tokens] |
1357 | 0 | group_scores = ggml_get_rows(ctx0, ggml_reshape_4d(ctx0, selection_groups, 1, selection_groups->ne[0], selection_groups->ne[1], selection_groups->ne[2]), group_scores); // [1, 2, n_expert_groups, n_tokens] |
1358 | | |
1359 | | // get top n_group_used expert groups |
1360 | 0 | group_scores = ggml_sum_rows(ctx0, ggml_reshape_3d(ctx0, group_scores, group_scores->ne[1], group_scores->ne[2], group_scores->ne[3])); // [1, n_expert_groups, n_tokens] |
1361 | 0 | group_scores = ggml_reshape_2d(ctx0, group_scores, group_scores->ne[1], group_scores->ne[2]); // [n_expert_groups, n_tokens] |
1362 | |
|
1363 | 0 | ggml_tensor * expert_groups = ggml_argsort_top_k(ctx0, group_scores, hparams.n_group_used); // [n_group_used, n_tokens] |
1364 | 0 | cb(expert_groups, "ffn_moe_group_topk", il); |
1365 | | |
1366 | | // mask out the other groups |
1367 | 0 | selection_probs = ggml_get_rows(ctx0, selection_groups, expert_groups); // [n_exp_per_group, n_group_used, n_tokens] |
1368 | 0 | selection_probs = ggml_set_rows(ctx0, ggml_fill(ctx0, selection_groups, -INFINITY), selection_probs, expert_groups); // [n_exp_per_group, n_expert_groups, n_tokens] |
1369 | 0 | selection_probs = ggml_reshape_2d(ctx0, selection_probs, n_expert, n_tokens); // [n_expert, n_tokens] |
1370 | 0 | cb(selection_probs, "ffn_moe_probs_masked", il); |
1371 | 0 | } |
1372 | | |
1373 | | // select experts |
1374 | 0 | ggml_tensor * selected_experts = ggml_argsort_top_k(ctx0, selection_probs, n_expert_used); // [n_expert_used, n_tokens] |
1375 | 0 | cb(selected_experts->src[0], "ffn_moe_argsort", il); |
1376 | 0 | cb(selected_experts, "ffn_moe_topk", il); |
1377 | |
|
1378 | 0 | if (arch == LLM_ARCH_GROVEMOE && n_expert != hparams.n_expert) { |
1379 | | // TODO: Use scalar div instead when/if implemented |
1380 | 0 | ggml_tensor * f_sel = ggml_cast(ctx0, selected_experts, GGML_TYPE_F32); |
1381 | 0 | selected_experts = ggml_cast(ctx0, ggml_scale(ctx0, f_sel, 1.0f / float(hparams.n_group_experts)), GGML_TYPE_I32); |
1382 | 0 | probs = ggml_reshape_3d(ctx0, probs, 1, hparams.n_expert, n_tokens); |
1383 | 0 | } else { |
1384 | 0 | probs = ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens); |
1385 | 0 | } |
1386 | |
|
1387 | 0 | ggml_tensor * weights = ggml_get_rows(ctx0, probs, selected_experts); // [1, n_expert_used, n_tokens] |
1388 | 0 | cb(weights, "ffn_moe_weights", il); |
1389 | | |
1390 | |
|
1391 | 0 | if (gating_op == LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX_WEIGHT) { |
1392 | 0 | weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); |
1393 | 0 | weights = ggml_soft_max(ctx0, weights); // [n_expert_used, n_tokens] |
1394 | 0 | weights = ggml_reshape_3d(ctx0, weights, 1, n_expert_used, n_tokens); |
1395 | 0 | cb(weights, "ffn_moe_weights_softmax", il); |
1396 | 0 | } |
1397 | |
|
1398 | 0 | if (norm_w) { |
1399 | 0 | weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); |
1400 | |
|
1401 | 0 | ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights); // [1, n_tokens] |
1402 | 0 | cb(weights_sum, "ffn_moe_weights_sum", il); |
1403 | | |
1404 | | // Avoid division by zero, clamp to smallest number representable by F16 |
1405 | 0 | weights_sum = ggml_clamp(ctx0, weights_sum, 6.103515625e-5, INFINITY); |
1406 | 0 | cb(weights_sum, "ffn_moe_weights_sum_clamped", il); |
1407 | |
|
1408 | 0 | weights = ggml_div(ctx0, weights, weights_sum); // [n_expert_used, n_tokens] |
1409 | 0 | cb(weights, "ffn_moe_weights_norm", il); |
1410 | |
|
1411 | 0 | weights = ggml_reshape_3d(ctx0, weights, 1, n_expert_used, n_tokens); |
1412 | 0 | } |
1413 | 0 | if (w_scale != 0.0f && w_scale != 1.0f) { |
1414 | 0 | weights = ggml_scale(ctx0, weights, w_scale); |
1415 | 0 | cb(weights, "ffn_moe_weights_scaled", il); |
1416 | 0 | } |
1417 | | |
1418 | | //call early so that topk-moe can be used |
1419 | 0 | ggml_build_forward_expand(gf, weights); |
1420 | |
|
1421 | 0 | cur = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); |
1422 | |
|
1423 | 0 | if (weight_before_ffn) { |
1424 | | // repeat cur to [n_embd, n_expert_used, n_tokens] |
1425 | 0 | ggml_tensor * repeated = ggml_repeat_4d(ctx0, cur, n_embd, n_expert_used, n_tokens, 1); |
1426 | 0 | cur = ggml_mul(ctx0, repeated, weights); |
1427 | 0 | cb(cur, "ffn_moe_weighted", il); |
1428 | 0 | } |
1429 | |
|
1430 | 0 | ggml_tensor * up = nullptr; |
1431 | 0 | ggml_tensor * experts = nullptr; |
1432 | |
|
1433 | 0 | if (gate_up_exps) { |
1434 | | // merged gate_up path: one mul_mat_id, then split into gate and up views |
1435 | 0 | ggml_tensor * gate_up = build_lora_mm_id(gate_up_exps, cur, selected_experts); // [n_ff*2, n_expert_used, n_tokens] |
1436 | 0 | cb(gate_up, "ffn_moe_gate_up", il); |
1437 | |
|
1438 | 0 | if (gate_up_exps_b) { |
1439 | 0 | gate_up = ggml_add_id(ctx0, gate_up, gate_up_exps_b, selected_experts); |
1440 | 0 | cb(gate_up, "ffn_moe_gate_up_biased", il); |
1441 | 0 | } |
1442 | | |
1443 | | // apply per-expert scale2 to merged gate_up (use up_exps_s since gate and up are fused) |
1444 | 0 | if (up_exps_s) { |
1445 | 0 | ggml_tensor * s = ggml_reshape_3d(ctx0, up_exps_s, 1, n_expert, 1); |
1446 | 0 | s = ggml_repeat_4d(ctx0, s, 1, n_expert, n_tokens, 1); |
1447 | 0 | s = ggml_get_rows(ctx0, s, selected_experts); // [1, n_expert_used, n_tokens] |
1448 | 0 | gate_up = ggml_mul(ctx0, gate_up, s); |
1449 | 0 | cb(gate_up, "ffn_moe_gate_up_scaled", il); |
1450 | 0 | } |
1451 | |
|
1452 | 0 | const int64_t n_ff = gate_up->ne[0] / 2; |
1453 | 0 | cur = ggml_view_3d(ctx0, gate_up, n_ff, gate_up->ne[1], gate_up->ne[2], gate_up->nb[1], gate_up->nb[2], 0); |
1454 | 0 | cb(cur, "ffn_moe_gate", il); |
1455 | 0 | up = ggml_view_3d(ctx0, gate_up, n_ff, gate_up->ne[1], gate_up->ne[2], gate_up->nb[1], gate_up->nb[2], n_ff * gate_up->nb[0]); |
1456 | 0 | cb(up, "ffn_moe_up", il); |
1457 | 0 | } else { |
1458 | | // separate gate and up path |
1459 | 0 | up = build_lora_mm_id(up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens] |
1460 | 0 | cb(up, "ffn_moe_up", il); |
1461 | |
|
1462 | 0 | if (up_exps_b) { |
1463 | 0 | up = ggml_add_id(ctx0, up, up_exps_b, selected_experts); |
1464 | 0 | cb(up, "ffn_moe_up_biased", il); |
1465 | 0 | } |
1466 | | |
1467 | | // apply per-expert scale2 to up |
1468 | 0 | if (up_exps_s) { |
1469 | 0 | ggml_tensor * s = ggml_reshape_3d(ctx0, up_exps_s, 1, n_expert, 1); |
1470 | 0 | s = ggml_repeat_4d(ctx0, s, 1, n_expert, n_tokens, 1); |
1471 | 0 | s = ggml_get_rows(ctx0, s, selected_experts); // [1, n_expert_used, n_tokens] |
1472 | 0 | up = ggml_mul(ctx0, up, s); |
1473 | 0 | cb(up, "ffn_moe_up_scaled", il); |
1474 | 0 | } |
1475 | |
|
1476 | 0 | if (gate_exps) { |
1477 | 0 | cur = build_lora_mm_id(gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens] |
1478 | 0 | cb(cur, "ffn_moe_gate", il); |
1479 | 0 | } else { |
1480 | 0 | cur = up; |
1481 | 0 | } |
1482 | |
|
1483 | 0 | if (gate_exps_b) { |
1484 | 0 | cur = ggml_add_id(ctx0, cur, gate_exps_b, selected_experts); |
1485 | 0 | cb(cur, "ffn_moe_gate_biased", il); |
1486 | 0 | } |
1487 | | |
1488 | | // apply per-expert scale2 to gate |
1489 | 0 | if (gate_exps_s) { |
1490 | 0 | ggml_tensor * s = ggml_reshape_3d(ctx0, gate_exps_s, 1, n_expert, 1); |
1491 | 0 | s = ggml_repeat_4d(ctx0, s, 1, n_expert, n_tokens, 1); |
1492 | 0 | s = ggml_get_rows(ctx0, s, selected_experts); // [1, n_expert_used, n_tokens] |
1493 | 0 | cur = ggml_mul(ctx0, cur, s); |
1494 | 0 | cb(cur, "ffn_moe_gate_scaled", il); |
1495 | 0 | } |
1496 | 0 | } |
1497 | |
|
1498 | 0 | const bool has_gate = gate_exps || gate_up_exps; |
1499 | |
|
1500 | 0 | switch (type_op) { |
1501 | 0 | case LLM_FFN_SILU: |
1502 | 0 | if (gate_exps) { |
1503 | | // Step35: per-layer clamp for routed experts |
1504 | 0 | if (arch == LLM_ARCH_STEP35 && il >= 0) { |
1505 | 0 | const float limit = hparams.swiglu_clamp_exp[il]; |
1506 | 0 | constexpr float eps = 1e-6f; |
1507 | 0 | if (limit > eps) { |
1508 | 0 | ggml_tensor * gate_act = ggml_silu(ctx0, cur); |
1509 | 0 | cb(gate_act, "ffn_moe_silu", il); |
1510 | 0 | gate_act = ggml_clamp(ctx0, gate_act, -INFINITY, limit); |
1511 | 0 | cb(gate_act, "ffn_moe_silu_clamped", il); |
1512 | |
|
1513 | 0 | up = ggml_clamp(ctx0, up, -limit, limit); |
1514 | 0 | cb(up, "ffn_moe_up_clamped", il); |
1515 | |
|
1516 | 0 | cur = ggml_mul(ctx0, gate_act, up); |
1517 | 0 | cb(cur, "ffn_moe_swiglu_limited", il); |
1518 | 0 | break; |
1519 | 0 | } |
1520 | 0 | } |
1521 | 0 | } |
1522 | | |
1523 | 0 | if (has_gate) { |
1524 | 0 | cur = ggml_swiglu_split(ctx0, cur, up); |
1525 | 0 | cb(cur, "ffn_moe_swiglu", il); |
1526 | 0 | } else { |
1527 | 0 | cur = ggml_silu(ctx0, cur); |
1528 | 0 | cb(cur, "ffn_moe_silu", il); |
1529 | 0 | } break; |
1530 | 0 | case LLM_FFN_GELU: |
1531 | 0 | if (has_gate) { |
1532 | 0 | cur = ggml_geglu_split(ctx0, cur, up); |
1533 | 0 | cb(cur, "ffn_moe_geglu", il); |
1534 | 0 | } else { |
1535 | 0 | cur = ggml_gelu(ctx0, cur); |
1536 | 0 | cb(cur, "ffn_moe_gelu", il); |
1537 | 0 | } break; |
1538 | 0 | case LLM_FFN_SWIGLU_OAI_MOE: |
1539 | 0 | { |
1540 | | // TODO: move to hparams? |
1541 | 0 | constexpr float alpha = 1.702f; |
1542 | 0 | constexpr float limit = 7.0f; |
1543 | 0 | cur = ggml_swiglu_oai(ctx0, cur, up, alpha, limit); |
1544 | 0 | cb(cur, "ffn_moe_swiglu_oai", il); |
1545 | 0 | } break; |
1546 | 0 | case LLM_FFN_RELU: |
1547 | 0 | if (has_gate) { |
1548 | 0 | cur = ggml_reglu_split(ctx0, cur, up); |
1549 | 0 | cb(cur, "ffn_moe_reglu", il); |
1550 | 0 | } else { |
1551 | 0 | cur = ggml_relu(ctx0, cur); |
1552 | 0 | cb(cur, "ffn_moe_relu", il); |
1553 | 0 | } break; |
1554 | 0 | case LLM_FFN_RELU_SQR: |
1555 | 0 | if (has_gate) { |
1556 | | // TODO: add support for gated squared relu |
1557 | 0 | GGML_ABORT("fatal error: gated squared relu not implemented"); |
1558 | 0 | } else { |
1559 | 0 | cur = ggml_relu(ctx0, cur); |
1560 | 0 | cur = ggml_sqr(ctx0, cur); |
1561 | 0 | cb(cur, "ffn_moe_relu_sqr", il); |
1562 | 0 | } break; |
1563 | 0 | default: |
1564 | 0 | GGML_ABORT("fatal error"); |
1565 | 0 | } |
1566 | | |
1567 | 0 | experts = build_lora_mm_id(down_exps, cur, selected_experts); // [n_embd, n_expert_used, n_tokens] |
1568 | 0 | cb(experts, "ffn_moe_down", il); |
1569 | |
|
1570 | 0 | if (down_exps_b) { |
1571 | 0 | experts = ggml_add_id(ctx0, experts, down_exps_b, selected_experts); |
1572 | 0 | cb(experts, "ffn_moe_down_biased", il); |
1573 | 0 | } |
1574 | | |
1575 | | // apply per-expert scale2 to down |
1576 | 0 | if (down_exps_s) { |
1577 | 0 | ggml_tensor * s = ggml_reshape_3d(ctx0, down_exps_s, 1, n_expert, 1); |
1578 | 0 | s = ggml_repeat_4d(ctx0, s, 1, n_expert, n_tokens, 1); |
1579 | 0 | s = ggml_get_rows(ctx0, s, selected_experts); // [1, n_expert_used, n_tokens] |
1580 | 0 | experts = ggml_mul(ctx0, experts, s); |
1581 | 0 | cb(experts, "ffn_moe_down_scaled", il); |
1582 | 0 | } |
1583 | |
|
1584 | 0 | if (!weight_before_ffn) { |
1585 | 0 | experts = ggml_mul(ctx0, experts, weights); |
1586 | 0 | cb(experts, "ffn_moe_weighted", il); |
1587 | 0 | } |
1588 | |
|
1589 | 0 | ggml_build_forward_expand(gf, experts); |
1590 | |
|
1591 | 0 | ggml_tensor * cur_experts[LLAMA_MAX_EXPERTS] = { nullptr }; |
1592 | |
|
1593 | 0 | assert(n_expert_used > 0); |
1594 | | |
1595 | | // order the views before the adds |
1596 | 0 | for (uint32_t i = 0; i < hparams.n_expert_used; ++i) { |
1597 | 0 | cur_experts[i] = ggml_view_2d(ctx0, experts, n_embd, n_tokens, experts->nb[2], i*experts->nb[1]); |
1598 | |
|
1599 | 0 | ggml_build_forward_expand(gf, cur_experts[i]); |
1600 | 0 | } |
1601 | | |
1602 | | // aggregate experts |
1603 | | // note: here we explicitly use hparams.n_expert_used instead of n_expert_used |
1604 | | // to avoid potentially a large number of add nodes during warmup |
1605 | | // ref: https://github.com/ggml-org/llama.cpp/pull/14753 |
1606 | 0 | ggml_tensor * moe_out = cur_experts[0]; |
1607 | |
|
1608 | 0 | for (uint32_t i = 1; i < hparams.n_expert_used; ++i) { |
1609 | 0 | moe_out = ggml_add(ctx0, moe_out, cur_experts[i]); |
1610 | |
|
1611 | 0 | ggml_build_forward_expand(gf, moe_out); |
1612 | 0 | } |
1613 | |
|
1614 | 0 | if (hparams.n_expert_used == 1) { |
1615 | | // avoid returning a non-contiguous tensor |
1616 | 0 | moe_out = ggml_cont(ctx0, moe_out); |
1617 | 0 | } |
1618 | |
|
1619 | 0 | cb(moe_out, "ffn_moe_out", il); |
1620 | |
|
1621 | 0 | return moe_out; |
1622 | 0 | } |
1623 | | |
1624 | | // input embeddings with optional lora |
1625 | 0 | ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd) const { |
1626 | 0 | const int64_t n_embd_inp = hparams.n_embd_inp(); |
1627 | 0 | const int64_t n_embd = hparams.n_embd; |
1628 | |
|
1629 | 0 | assert(n_embd_inp >= n_embd); |
1630 | |
|
1631 | 0 | auto inp = std::make_unique<llm_graph_input_embd>(n_embd_inp); |
1632 | |
|
1633 | 0 | inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_tokens); |
1634 | 0 | cb(inp->tokens, "inp_tokens", -1); |
1635 | 0 | ggml_set_input(inp->tokens); |
1636 | 0 | res->t_inp_tokens = inp->tokens; |
1637 | |
|
1638 | 0 | inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd_inp, ubatch.n_tokens); |
1639 | 0 | cb(inp->embd, "inp_embd", -1); |
1640 | 0 | ggml_set_input(inp->embd); |
1641 | | |
1642 | | // select one of the 2 inputs, based on the batch contents |
1643 | | // ref: https://github.com/ggml-org/llama.cpp/pull/18550 |
1644 | 0 | std::array<ggml_tensor *, 2> inps; |
1645 | | |
1646 | | // token embeddings path (ubatch.token != nullptr) |
1647 | 0 | { |
1648 | 0 | auto & cur = inps[0]; |
1649 | |
|
1650 | 0 | cur = ggml_get_rows(ctx0, tok_embd, inp->tokens); |
1651 | | |
1652 | | // apply lora for embedding tokens if needed |
1653 | 0 | for (const auto & lora : *loras) { |
1654 | 0 | llama_adapter_lora_weight * lw = lora.first->get_weight(tok_embd); |
1655 | 0 | if (lw == nullptr) { |
1656 | 0 | continue; |
1657 | 0 | } |
1658 | | |
1659 | 0 | const float adapter_scale = lora.second; |
1660 | 0 | const float scale = lw->get_scale(lora.first->alpha, adapter_scale); |
1661 | |
|
1662 | 0 | ggml_tensor * inpL_delta = ggml_scale(ctx0, ggml_mul_mat( |
1663 | 0 | ctx0, lw->b, // non-transposed lora_b |
1664 | 0 | ggml_get_rows(ctx0, lw->a, inp->tokens) |
1665 | 0 | ), scale); |
1666 | |
|
1667 | 0 | cur = ggml_add(ctx0, cur, inpL_delta); |
1668 | 0 | } |
1669 | |
|
1670 | 0 | if (n_embd_inp != n_embd) { |
1671 | 0 | cur = ggml_pad(ctx0, cur, hparams.n_embd_inp() - n_embd, 0, 0, 0); |
1672 | 0 | } |
1673 | 0 | } |
1674 | | |
1675 | | // vector embeddings path (ubatch.embd != nullptr) |
1676 | 0 | { |
1677 | 0 | auto & cur = inps[1]; |
1678 | |
|
1679 | 0 | cur = inp->embd; |
1680 | 0 | } |
1681 | |
|
1682 | 0 | assert(ggml_are_same_shape (inps[0], inps[1])); |
1683 | 0 | assert(ggml_are_same_stride(inps[0], inps[1])); |
1684 | |
|
1685 | 0 | ggml_tensor * cur = ggml_build_forward_select(gf, inps.data(), inps.size(), ubatch.token ? 0 : 1); |
1686 | |
|
1687 | 0 | if (n_embd_inp != n_embd) { |
1688 | 0 | cur = ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0); |
1689 | 0 | } |
1690 | |
|
1691 | 0 | res->t_inp_embd = cur; |
1692 | | |
1693 | | // For Granite architecture |
1694 | 0 | if (hparams.f_embedding_scale != 0.0f) { |
1695 | 0 | cur = ggml_scale(ctx0, cur, hparams.f_embedding_scale); |
1696 | 0 | } |
1697 | |
|
1698 | 0 | cb(cur, "embd", -1); |
1699 | |
|
1700 | 0 | res->add_input(std::move(inp)); |
1701 | | |
1702 | | // make sure the produced embeddings are immediately materialized in the ggml graph |
1703 | | // ref: https://github.com/ggml-org/llama.cpp/pull/18599 |
1704 | 0 | ggml_build_forward_expand(gf, cur); |
1705 | |
|
1706 | 0 | return cur; |
1707 | 0 | } |
1708 | | |
1709 | 0 | ggml_tensor * llm_graph_context::build_inp_pos() const { |
1710 | 0 | auto inp = std::make_unique<llm_graph_input_pos>(hparams.n_pos_per_embd()); |
1711 | |
|
1712 | 0 | auto & cur = inp->pos; |
1713 | |
|
1714 | 0 | cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, (int64_t)n_tokens*hparams.n_pos_per_embd()); |
1715 | 0 | ggml_set_input(cur); |
1716 | |
|
1717 | 0 | res->add_input(std::move(inp)); |
1718 | |
|
1719 | 0 | return cur; |
1720 | 0 | } |
1721 | | |
1722 | 0 | ggml_tensor * llm_graph_context::build_inp_attn_scale() const { |
1723 | 0 | auto inp = std::make_unique<llm_graph_input_attn_temp>(hparams.n_attn_temp_floor_scale, hparams.f_attn_temp_scale, hparams.f_attn_temp_offset); |
1724 | |
|
1725 | 0 | auto & cur = inp->attn_scale; |
1726 | | |
1727 | | // this need to be 1x1xN for broadcasting |
1728 | 0 | cur = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 1, 1, n_tokens); |
1729 | 0 | ggml_set_input(cur); |
1730 | 0 | ggml_set_name(cur, "attn_scale"); |
1731 | |
|
1732 | 0 | res->add_input(std::move(inp)); |
1733 | |
|
1734 | 0 | return cur; |
1735 | 0 | } |
1736 | | |
1737 | 0 | ggml_tensor * llm_graph_context::build_inp_out_ids() const { |
1738 | | // note: when all tokens are output, we could skip this optimization to spare the ggml_get_rows() calls, |
1739 | | // but this would make the graph topology depend on the number of output tokens, which can interfere with |
1740 | | // features that require constant topology such as pipeline parallelism |
1741 | | // ref: https://github.com/ggml-org/llama.cpp/pull/14275#issuecomment-2987424471 |
1742 | | //if (n_outputs < n_tokens) { |
1743 | | // return nullptr; |
1744 | | //} |
1745 | |
|
1746 | 0 | auto inp = std::make_unique<llm_graph_input_out_ids>(hparams, cparams, n_outputs); |
1747 | |
|
1748 | 0 | auto & cur = inp->out_ids; |
1749 | |
|
1750 | 0 | cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs); |
1751 | 0 | ggml_set_input(cur); |
1752 | |
|
1753 | 0 | res->add_input(std::move(inp)); |
1754 | |
|
1755 | 0 | return cur; |
1756 | 0 | } |
1757 | | |
1758 | 0 | ggml_tensor * llm_graph_context::build_inp_mean() const { |
1759 | 0 | auto inp = std::make_unique<llm_graph_input_mean>(cparams); |
1760 | |
|
1761 | 0 | auto & cur = inp->mean; |
1762 | |
|
1763 | 0 | cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, ubatch.n_seqs_unq); |
1764 | 0 | ggml_set_input(cur); |
1765 | |
|
1766 | 0 | res->add_input(std::move(inp)); |
1767 | |
|
1768 | 0 | return cur; |
1769 | 0 | } |
1770 | | |
1771 | 0 | ggml_tensor * llm_graph_context::build_inp_cls() const { |
1772 | 0 | auto inp = std::make_unique<llm_graph_input_cls>(cparams, arch); |
1773 | |
|
1774 | 0 | auto & cur = inp->cls; |
1775 | |
|
1776 | 0 | cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_seqs_unq); |
1777 | 0 | ggml_set_input(cur); |
1778 | |
|
1779 | 0 | res->add_input(std::move(inp)); |
1780 | |
|
1781 | 0 | return cur; |
1782 | 0 | } |
1783 | | |
1784 | 0 | ggml_tensor * llm_graph_context::build_inp_cross_embd() const { |
1785 | 0 | auto inp = std::make_unique<llm_graph_input_cross_embd>(cross); |
1786 | |
|
1787 | 0 | auto & cur = inp->cross_embd; |
1788 | | |
1789 | | // if we have the output embeddings from the encoder, use them directly |
1790 | | // TODO: needs more work to be correct, for now just use the tensor shape |
1791 | | //if (cross->t_embd) { |
1792 | | // cur = ggml_view_tensor(ctx0, cross->t_embd); |
1793 | | |
1794 | | // return cur; |
1795 | | //} |
1796 | |
|
1797 | 0 | const auto n_embd = !cross->v_embd.empty() ? cross->n_embd : hparams.n_embd_inp(); |
1798 | 0 | const auto n_enc = !cross->v_embd.empty() ? cross->n_enc : hparams.n_ctx_train; |
1799 | |
|
1800 | 0 | cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_enc); |
1801 | 0 | ggml_set_input(cur); |
1802 | |
|
1803 | 0 | res->add_input(std::move(inp)); |
1804 | |
|
1805 | 0 | return cur; |
1806 | 0 | } |
1807 | | |
1808 | 0 | ggml_tensor * llm_graph_context::build_inp_pos_bucket_enc() const { |
1809 | 0 | auto inp = std::make_unique<llm_graph_input_pos_bucket>(hparams); |
1810 | |
|
1811 | 0 | auto & cur = inp->pos_bucket; |
1812 | |
|
1813 | 0 | cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens); |
1814 | 0 | ggml_set_input(cur); |
1815 | |
|
1816 | 0 | res->add_input(std::move(inp)); |
1817 | |
|
1818 | 0 | return cur; |
1819 | 0 | } |
1820 | | |
1821 | 0 | ggml_tensor * llm_graph_context::build_inp_pos_bucket_dec() const { |
1822 | 0 | const auto * mctx_cur = static_cast<const llama_kv_cache_context *>(mctx); |
1823 | |
|
1824 | 0 | auto inp = std::make_unique<llm_graph_input_pos_bucket_kv>(hparams, mctx_cur); |
1825 | |
|
1826 | 0 | const auto n_kv = mctx_cur->get_n_kv(); |
1827 | |
|
1828 | 0 | auto & cur = inp->pos_bucket; |
1829 | |
|
1830 | 0 | cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens); |
1831 | 0 | ggml_set_input(cur); |
1832 | |
|
1833 | 0 | res->add_input(std::move(inp)); |
1834 | |
|
1835 | 0 | return cur; |
1836 | 0 | } |
1837 | | |
1838 | 0 | ggml_tensor * llm_graph_context::build_pos_bias(ggml_tensor * pos_bucket, ggml_tensor * attn_rel_b) const { |
1839 | 0 | ggml_tensor * pos_bucket_1d = ggml_reshape_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1]); |
1840 | 0 | cb(pos_bucket_1d, "pos_bucket_1d", -1); |
1841 | |
|
1842 | 0 | ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d); |
1843 | |
|
1844 | 0 | pos_bias = ggml_reshape_3d(ctx0, pos_bias, pos_bias->ne[0], pos_bucket->ne[0], pos_bucket->ne[1]); |
1845 | 0 | pos_bias = ggml_permute (ctx0, pos_bias, 2, 0, 1, 3); |
1846 | 0 | pos_bias = ggml_cont (ctx0, pos_bias); |
1847 | |
|
1848 | 0 | cb(pos_bias, "pos_bias", -1); |
1849 | |
|
1850 | 0 | return pos_bias; |
1851 | 0 | } |
1852 | | |
1853 | | ggml_tensor * llm_graph_context::build_attn_mha( |
1854 | | ggml_tensor * q, |
1855 | | ggml_tensor * k, |
1856 | | ggml_tensor * v, |
1857 | | ggml_tensor * kq_b, |
1858 | | ggml_tensor * kq_mask, |
1859 | | ggml_tensor * sinks, |
1860 | | ggml_tensor * v_mla, |
1861 | | float kq_scale, |
1862 | 0 | int il) const { |
1863 | 0 | const bool v_trans = v->nb[1] > v->nb[2]; |
1864 | | |
1865 | | // split the batch into streams if needed |
1866 | 0 | const auto n_stream = k->ne[3]; |
1867 | |
|
1868 | 0 | q = ggml_view_4d(ctx0, q, q->ne[0], q->ne[1], q->ne[2]/n_stream, n_stream, q->nb[1], q->nb[2], q->nb[3]/n_stream, 0); |
1869 | |
|
1870 | 0 | q = ggml_permute(ctx0, q, 0, 2, 1, 3); |
1871 | 0 | k = ggml_permute(ctx0, k, 0, 2, 1, 3); |
1872 | 0 | v = ggml_permute(ctx0, v, 0, 2, 1, 3); |
1873 | |
|
1874 | 0 | ggml_tensor * cur; |
1875 | |
|
1876 | 0 | const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr; |
1877 | 0 | if (use_flash_attn) { |
1878 | 0 | GGML_ASSERT(kq_b == nullptr && "Flash attention does not support KQ bias yet"); |
1879 | |
|
1880 | 0 | if (v_trans) { |
1881 | 0 | v = ggml_transpose(ctx0, v); |
1882 | 0 | } |
1883 | | |
1884 | | // this can happen when KV cache is not used (e.g. an embedding model with non-causal attn) |
1885 | 0 | if (k->type == GGML_TYPE_F32) { |
1886 | 0 | k = ggml_cast(ctx0, k, GGML_TYPE_F16); |
1887 | 0 | } |
1888 | |
|
1889 | 0 | if (v->type == GGML_TYPE_F32) { |
1890 | 0 | v = ggml_cast(ctx0, v, GGML_TYPE_F16); |
1891 | 0 | } |
1892 | |
|
1893 | 0 | cur = ggml_flash_attn_ext(ctx0, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias, |
1894 | 0 | hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f); |
1895 | 0 | cb(cur, LLAMA_TENSOR_NAME_FATTN, il); |
1896 | |
|
1897 | 0 | ggml_flash_attn_ext_add_sinks(cur, sinks); |
1898 | 0 | ggml_flash_attn_ext_set_prec (cur, GGML_PREC_F32); |
1899 | |
|
1900 | 0 | if (v_mla) { |
1901 | | #if 0 |
1902 | | // v_mla can be applied as a matrix-vector multiplication with broadcasting across dimension 3 == n_tokens. |
1903 | | // However, the code is optimized for dimensions 0 and 1 being large, so this is inefficient. |
1904 | | cur = ggml_reshape_4d(ctx0, cur, v_mla->ne[0], 1, n_head, n_tokens); |
1905 | | cur = ggml_mul_mat(ctx0, v_mla, cur); |
1906 | | #else |
1907 | | // It's preferable to do the calculation as a matrix-matrix multiplication with n_tokens in dimension 1. |
1908 | | // The permutations are noops and only change how the tensor data is interpreted. |
1909 | 0 | cur = ggml_permute(ctx0, cur, 0, 2, 1, 3); |
1910 | 0 | cur = ggml_mul_mat(ctx0, v_mla, cur); |
1911 | 0 | cb(cur, "fattn_mla", il); |
1912 | 0 | cur = ggml_permute(ctx0, cur, 0, 2, 1, 3); |
1913 | 0 | cur = ggml_cont(ctx0, cur); // Needed because ggml_reshape_2d expects contiguous inputs. |
1914 | 0 | #endif |
1915 | 0 | } |
1916 | |
|
1917 | 0 | cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); |
1918 | 0 | } else { |
1919 | 0 | ggml_tensor * kq = ggml_mul_mat(ctx0, k, q); |
1920 | 0 | cb(kq, "kq", il); |
1921 | | |
1922 | | // note: this op tends to require high floating point range |
1923 | | // while for some models F16 is enough, for others it is not, so we default to F32 here |
1924 | 0 | ggml_mul_mat_set_prec(kq, GGML_PREC_F32); |
1925 | |
|
1926 | 0 | if (arch == LLM_ARCH_GROK) { |
1927 | | // need to do the following: |
1928 | | // multiply by attn_output_multiplier |
1929 | | // and then : |
1930 | | // kq = 30 * tanh(kq / 30) |
1931 | | // before the softmax below |
1932 | |
|
1933 | 0 | kq = ggml_tanh(ctx0, ggml_scale(ctx0, kq, hparams.f_attn_out_scale / hparams.f_attn_logit_softcapping)); |
1934 | 0 | cb(kq, "kq_tanh", il); |
1935 | 0 | kq = ggml_scale(ctx0, kq, hparams.f_attn_logit_softcapping); |
1936 | 0 | cb(kq, "kq_scaled", il); |
1937 | 0 | } |
1938 | |
|
1939 | 0 | if (hparams.attn_soft_cap) { |
1940 | 0 | kq = ggml_scale(ctx0, kq, 1.0f / hparams.f_attn_logit_softcapping); |
1941 | 0 | cb(kq, "kq_scaled_1", il); |
1942 | 0 | kq = ggml_tanh (ctx0, kq); |
1943 | 0 | cb(kq, "kq_tanh", il); |
1944 | 0 | kq = ggml_scale(ctx0, kq, hparams.f_attn_logit_softcapping); |
1945 | 0 | cb(kq, "kq_scaled_2", il); |
1946 | 0 | } |
1947 | |
|
1948 | 0 | if (kq_b) { |
1949 | 0 | kq = ggml_add(ctx0, kq, kq_b); |
1950 | 0 | cb(kq, "kq_plus_kq_b", il); |
1951 | 0 | } |
1952 | |
|
1953 | 0 | kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias); |
1954 | 0 | ggml_soft_max_add_sinks(kq, sinks); |
1955 | 0 | cb(kq, "kq_soft_max", il); |
1956 | |
|
1957 | 0 | if (!v_trans) { |
1958 | | // note: avoid this branch |
1959 | 0 | v = ggml_cont(ctx0, ggml_transpose(ctx0, v)); |
1960 | 0 | cb(v, "v_cont", il); |
1961 | 0 | } |
1962 | |
|
1963 | 0 | ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq); |
1964 | 0 | cb(kqv, "kqv", il); |
1965 | | |
1966 | | // for MLA with the absorption optimization, we need to "decompress" from MQA back to MHA |
1967 | 0 | if (v_mla) { |
1968 | 0 | kqv = ggml_mul_mat(ctx0, v_mla, kqv); |
1969 | 0 | cb(kqv, "kqv_mla", il); |
1970 | 0 | } |
1971 | |
|
1972 | 0 | cur = ggml_permute(ctx0, kqv, 0, 2, 1, 3); |
1973 | | |
1974 | | // recombine streams |
1975 | 0 | cur = ggml_cont_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); |
1976 | |
|
1977 | 0 | if (!cparams.offload_kqv) { |
1978 | | // all nodes between the KV store and the attention output are run on the CPU |
1979 | 0 | ggml_backend_sched_set_tensor_backend(sched, cur, backend_cpu); |
1980 | 0 | } |
1981 | 0 | } |
1982 | |
|
1983 | 0 | ggml_build_forward_expand(gf, cur); |
1984 | |
|
1985 | 0 | return cur; |
1986 | 0 | } |
1987 | | |
1988 | 0 | llm_graph_input_attn_no_cache * llm_graph_context::build_attn_inp_no_cache() const { |
1989 | 0 | auto inp = std::make_unique<llm_graph_input_attn_no_cache>(hparams, cparams); |
1990 | | |
1991 | | // note: there is no KV cache, so the number of KV values is equal to the number of tokens in the batch |
1992 | 0 | inp->self_kq_mask = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens, 1, 1); |
1993 | 0 | ggml_set_input(inp->self_kq_mask); |
1994 | |
|
1995 | 0 | inp->self_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask, GGML_TYPE_F16) : inp->self_kq_mask; |
1996 | |
|
1997 | 0 | if (hparams.swa_type != LLAMA_SWA_TYPE_NONE) { |
1998 | 0 | inp->self_kq_mask_swa = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens, 1, 1); |
1999 | 0 | ggml_set_input(inp->self_kq_mask_swa); |
2000 | |
|
2001 | 0 | 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; |
2002 | 0 | } else { |
2003 | 0 | inp->self_kq_mask_swa = nullptr; |
2004 | 0 | inp->self_kq_mask_swa_cnv = nullptr; |
2005 | 0 | } |
2006 | |
|
2007 | 0 | return (llm_graph_input_attn_no_cache *) res->add_input(std::move(inp)); |
2008 | 0 | } |
2009 | | |
2010 | | ggml_tensor * llm_graph_context::build_attn( |
2011 | | llm_graph_input_attn_no_cache * inp, |
2012 | | ggml_tensor * wo, |
2013 | | ggml_tensor * wo_b, |
2014 | | ggml_tensor * q_cur, |
2015 | | ggml_tensor * k_cur, |
2016 | | ggml_tensor * v_cur, |
2017 | | ggml_tensor * kq_b, |
2018 | | ggml_tensor * sinks, |
2019 | | ggml_tensor * v_mla, |
2020 | | float kq_scale, |
2021 | 0 | int il) const { |
2022 | 0 | GGML_UNUSED(n_tokens); |
2023 | | |
2024 | | // these nodes are added to the graph together so that they are not reordered |
2025 | | // by doing so, the number of splits in the graph is reduced |
2026 | 0 | ggml_build_forward_expand(gf, q_cur); |
2027 | 0 | ggml_build_forward_expand(gf, k_cur); |
2028 | 0 | ggml_build_forward_expand(gf, v_cur); |
2029 | |
|
2030 | 0 | const bool is_swa = hparams.is_swa(il); |
2031 | |
|
2032 | 0 | const auto & kq_mask = is_swa ? inp->get_kq_mask_swa() : inp->get_kq_mask(); |
2033 | | |
2034 | | // [TAG_NO_CACHE_PAD] |
2035 | | // TODO: if ubatch.equal_seqs() == true, we can split the three tensors below into ubatch.n_seqs_unq streams |
2036 | | // but it might not be worth it: https://github.com/ggml-org/llama.cpp/pull/15636 |
2037 | | //assert(!ubatch.equal_seqs() || (k_cur->ne[3] == 1 && k_cur->ne[3] == ubatch.n_seqs_unq)); |
2038 | |
|
2039 | 0 | ggml_tensor * q = q_cur; |
2040 | 0 | ggml_tensor * k = k_cur; |
2041 | 0 | ggml_tensor * v = v_cur; |
2042 | |
|
2043 | 0 | ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, kq_scale, il); |
2044 | 0 | cb(cur, "kqv_out", il); |
2045 | |
|
2046 | 0 | if (wo) { |
2047 | 0 | cur = build_lora_mm(wo, cur); |
2048 | 0 | } |
2049 | |
|
2050 | 0 | if (wo_b) { |
2051 | | //cb(cur, "kqv_wo", il); |
2052 | 0 | } |
2053 | |
|
2054 | 0 | if (wo_b) { |
2055 | 0 | cur = ggml_add(ctx0, cur, wo_b); |
2056 | 0 | } |
2057 | |
|
2058 | 0 | return cur; |
2059 | 0 | } |
2060 | | |
2061 | | static std::unique_ptr<llm_graph_input_attn_kv> build_attn_inp_kv_impl( |
2062 | | ggml_context * ctx0, |
2063 | | const llama_ubatch & ubatch, |
2064 | | const llama_hparams & hparams, |
2065 | | const llama_cparams & cparams, |
2066 | 0 | const llama_kv_cache_context * mctx_cur) { |
2067 | |
|
2068 | 0 | auto inp = std::make_unique<llm_graph_input_attn_kv>(hparams, cparams, mctx_cur); |
2069 | |
|
2070 | 0 | { |
2071 | 0 | GGML_ASSERT(hparams.swa_type == LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache_iswa for SWA"); |
2072 | |
|
2073 | 0 | inp->self_k_idxs = mctx_cur->build_input_k_idxs(ctx0, ubatch); |
2074 | 0 | inp->self_v_idxs = mctx_cur->build_input_v_idxs(ctx0, ubatch); |
2075 | |
|
2076 | 0 | inp->self_kq_mask = build_attn_inp_kq_mask(ctx0, mctx_cur, ubatch, cparams); |
2077 | 0 | inp->self_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask, GGML_TYPE_F16) : inp->self_kq_mask; |
2078 | 0 | } |
2079 | |
|
2080 | 0 | inp->self_k_rot = mctx_cur->build_input_k_rot(ctx0); |
2081 | 0 | inp->self_v_rot = mctx_cur->build_input_v_rot(ctx0); |
2082 | |
|
2083 | 0 | return inp; |
2084 | 0 | } |
2085 | | |
2086 | 0 | llm_graph_input_attn_kv * llm_graph_context::build_attn_inp_kv() const { |
2087 | 0 | const auto * mctx_cur = static_cast<const llama_kv_cache_context *>(mctx); |
2088 | |
|
2089 | 0 | auto inp = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur); |
2090 | |
|
2091 | 0 | return (llm_graph_input_attn_kv *) res->add_input(std::move(inp)); |
2092 | 0 | } |
2093 | | |
2094 | | ggml_tensor * llm_graph_context::build_attn( |
2095 | | llm_graph_input_attn_kv * inp, |
2096 | | ggml_tensor * wo, |
2097 | | ggml_tensor * wo_b, |
2098 | | ggml_tensor * q_cur, |
2099 | | ggml_tensor * k_cur, |
2100 | | ggml_tensor * v_cur, |
2101 | | ggml_tensor * kq_b, |
2102 | | ggml_tensor * sinks, |
2103 | | ggml_tensor * v_mla, // TODO: remove |
2104 | | float kq_scale, |
2105 | 0 | int il) const { |
2106 | 0 | GGML_ASSERT(v_mla == nullptr); |
2107 | |
|
2108 | 0 | if (inp->self_k_rot) { |
2109 | 0 | q_cur = ggml_mul_mat_aux(ctx0, q_cur, inp->self_k_rot); |
2110 | 0 | k_cur = ggml_mul_mat_aux(ctx0, k_cur, inp->self_k_rot); |
2111 | 0 | } |
2112 | |
|
2113 | 0 | if (inp->self_v_rot) { |
2114 | 0 | v_cur = ggml_mul_mat_aux(ctx0, v_cur, inp->self_v_rot); |
2115 | 0 | } |
2116 | | |
2117 | | // these nodes are added to the graph together so that they are not reordered |
2118 | | // by doing so, the number of splits in the graph is reduced |
2119 | | // expand k later to enable rope fusion which directly writes into k-v cache |
2120 | 0 | ggml_build_forward_expand(gf, q_cur); |
2121 | 0 | ggml_build_forward_expand(gf, v_cur); |
2122 | 0 | ggml_build_forward_expand(gf, k_cur); |
2123 | |
|
2124 | 0 | const auto * mctx_cur = inp->mctx; |
2125 | | |
2126 | | // store to KV cache |
2127 | 0 | { |
2128 | 0 | const auto & k_idxs = inp->get_k_idxs(); |
2129 | 0 | const auto & v_idxs = inp->get_v_idxs(); |
2130 | |
|
2131 | 0 | ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); |
2132 | 0 | ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); |
2133 | 0 | } |
2134 | |
|
2135 | 0 | const auto & kq_mask = inp->get_kq_mask(); |
2136 | |
|
2137 | 0 | ggml_tensor * q = q_cur; |
2138 | 0 | ggml_tensor * k = mctx_cur->get_k(ctx0, il); |
2139 | 0 | ggml_tensor * v = mctx_cur->get_v(ctx0, il); |
2140 | |
|
2141 | 0 | ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, kq_scale, il); |
2142 | 0 | cb(cur, "kqv_out", il); |
2143 | |
|
2144 | 0 | if (inp->self_v_rot) { |
2145 | 0 | cur = ggml_mul_mat_aux(ctx0, cur, inp->self_v_rot); |
2146 | 0 | } |
2147 | |
|
2148 | 0 | if (wo) { |
2149 | 0 | cur = build_lora_mm(wo, cur); |
2150 | 0 | if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE || arch == LLM_ARCH_JAIS2) { |
2151 | | // GLM4, GLM4_MOE, and JAIS2 seem to have numerical issues with half-precision accumulators |
2152 | 0 | ggml_mul_mat_set_prec(cur, GGML_PREC_F32); |
2153 | 0 | } |
2154 | 0 | } |
2155 | |
|
2156 | 0 | if (wo_b) { |
2157 | 0 | cur = ggml_add(ctx0, cur, wo_b); |
2158 | 0 | } |
2159 | |
|
2160 | 0 | return cur; |
2161 | 0 | } |
2162 | | |
2163 | | static std::unique_ptr<llm_graph_input_attn_k> build_attn_inp_k_impl( |
2164 | | ggml_context * ctx0, |
2165 | | const llama_ubatch & ubatch, |
2166 | | const llama_hparams & hparams, |
2167 | | const llama_cparams & cparams, |
2168 | 0 | const llama_kv_cache_context * mctx_cur) { |
2169 | |
|
2170 | 0 | auto inp = std::make_unique<llm_graph_input_attn_k>(hparams, cparams, mctx_cur); |
2171 | |
|
2172 | 0 | { |
2173 | 0 | GGML_ASSERT(hparams.swa_type == LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache_iswa for SWA"); |
2174 | |
|
2175 | 0 | inp->self_k_idxs = mctx_cur->build_input_k_idxs(ctx0, ubatch); |
2176 | |
|
2177 | 0 | inp->self_kq_mask = build_attn_inp_kq_mask(ctx0, mctx_cur, ubatch, cparams); |
2178 | 0 | inp->self_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask, GGML_TYPE_F16) : inp->self_kq_mask; |
2179 | 0 | } |
2180 | |
|
2181 | 0 | return inp; |
2182 | 0 | } |
2183 | | |
2184 | 0 | llm_graph_input_attn_k * llm_graph_context::build_attn_inp_k() const { |
2185 | 0 | const auto * mctx_cur = static_cast<const llama_kv_cache_context *>(mctx); |
2186 | |
|
2187 | 0 | auto inp = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur); |
2188 | |
|
2189 | 0 | return (llm_graph_input_attn_k *) res->add_input(std::move(inp)); |
2190 | 0 | } |
2191 | | |
2192 | | ggml_tensor * llm_graph_context::build_attn( |
2193 | | llm_graph_input_attn_k * inp, |
2194 | | ggml_tensor * wo, |
2195 | | ggml_tensor * wo_b, |
2196 | | ggml_tensor * q_cur, |
2197 | | ggml_tensor * k_cur, |
2198 | | ggml_tensor * v_cur, |
2199 | | ggml_tensor * kq_b, |
2200 | | ggml_tensor * sinks, |
2201 | | ggml_tensor * v_mla, |
2202 | | float kq_scale, |
2203 | 0 | int il) const { |
2204 | | // these nodes are added to the graph together so that they are not reordered |
2205 | | // by doing so, the number of splits in the graph is reduced |
2206 | | // expand k later to enable rope fusion which directly writes into k-v cache |
2207 | 0 | ggml_build_forward_expand(gf, q_cur); |
2208 | 0 | ggml_build_forward_expand(gf, v_cur); |
2209 | 0 | ggml_build_forward_expand(gf, k_cur); |
2210 | |
|
2211 | 0 | const auto * mctx_cur = inp->mctx; |
2212 | | |
2213 | | // store to KV cache |
2214 | 0 | { |
2215 | 0 | const auto & k_idxs = inp->get_k_idxs(); |
2216 | |
|
2217 | 0 | ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); |
2218 | 0 | } |
2219 | |
|
2220 | 0 | const auto & kq_mask = inp->get_kq_mask(); |
2221 | |
|
2222 | 0 | ggml_tensor * q = q_cur; |
2223 | 0 | ggml_tensor * k = mctx_cur->get_k(ctx0, il); |
2224 | 0 | ggml_tensor * v = ggml_view_4d(ctx0, k, v_cur->ne[0], k->ne[1], k->ne[2], k->ne[3], k->nb[1], k->nb[2], k->nb[3], 0); |
2225 | |
|
2226 | 0 | ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, kq_scale, il); |
2227 | 0 | cb(cur, "kqv_out", il); |
2228 | |
|
2229 | 0 | if (wo) { |
2230 | 0 | cur = build_lora_mm(wo, cur); |
2231 | 0 | if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE) { |
2232 | | // GLM4 and GLM4_MOE seem to have numerical issues with half-precision accumulators |
2233 | 0 | ggml_mul_mat_set_prec(cur, GGML_PREC_F32); |
2234 | 0 | } |
2235 | 0 | } |
2236 | |
|
2237 | 0 | if (wo_b) { |
2238 | 0 | cur = ggml_add(ctx0, cur, wo_b); |
2239 | 0 | } |
2240 | |
|
2241 | 0 | return cur; |
2242 | 0 | } |
2243 | | |
2244 | | ggml_tensor * llm_graph_context::build_attn( |
2245 | | llm_graph_input_attn_kv_iswa * inp, |
2246 | | ggml_tensor * wo, |
2247 | | ggml_tensor * wo_b, |
2248 | | ggml_tensor * q_cur, |
2249 | | ggml_tensor * k_cur, |
2250 | | ggml_tensor * v_cur, |
2251 | | ggml_tensor * kq_b, |
2252 | | ggml_tensor * sinks, |
2253 | | ggml_tensor * v_mla, |
2254 | | float kq_scale, |
2255 | 0 | int il) const { |
2256 | 0 | const bool is_swa = hparams.is_swa(il); |
2257 | |
|
2258 | 0 | auto * k_rot = is_swa ? inp->self_k_rot_swa : inp->self_k_rot; |
2259 | 0 | auto * v_rot = is_swa ? inp->self_v_rot_swa : inp->self_v_rot; |
2260 | |
|
2261 | 0 | if (k_rot) { |
2262 | 0 | q_cur = ggml_mul_mat_aux(ctx0, q_cur, k_rot); |
2263 | 0 | if (k_cur) { |
2264 | 0 | k_cur = ggml_mul_mat_aux(ctx0, k_cur, k_rot); |
2265 | 0 | } |
2266 | 0 | } |
2267 | 0 | if (v_rot) { |
2268 | 0 | if (v_cur) { |
2269 | 0 | v_cur = ggml_mul_mat_aux(ctx0, v_cur, v_rot); |
2270 | 0 | } |
2271 | 0 | } |
2272 | | |
2273 | | // these nodes are added to the graph together so that they are not reordered |
2274 | | // by doing so, the number of splits in the graph is reduced |
2275 | 0 | ggml_build_forward_expand(gf, q_cur); |
2276 | |
|
2277 | 0 | if (k_cur) { |
2278 | 0 | ggml_build_forward_expand(gf, k_cur); |
2279 | 0 | } |
2280 | |
|
2281 | 0 | if (v_cur) { |
2282 | 0 | ggml_build_forward_expand(gf, v_cur); |
2283 | 0 | } |
2284 | |
|
2285 | 0 | const auto * mctx_iswa = inp->mctx; |
2286 | |
|
2287 | 0 | const auto * mctx_cur = is_swa ? mctx_iswa->get_swa() : mctx_iswa->get_base(); |
2288 | | |
2289 | | // optionally store to KV cache |
2290 | 0 | if (k_cur) { |
2291 | 0 | const auto & k_idxs = is_swa ? inp->get_k_idxs_swa() : inp->get_k_idxs(); |
2292 | |
|
2293 | 0 | ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); |
2294 | 0 | } |
2295 | |
|
2296 | 0 | if (v_cur) { |
2297 | 0 | const auto & v_idxs = is_swa ? inp->get_v_idxs_swa() : inp->get_v_idxs(); |
2298 | |
|
2299 | 0 | ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); |
2300 | 0 | } |
2301 | |
|
2302 | 0 | const auto & kq_mask = is_swa ? inp->get_kq_mask_swa() : inp->get_kq_mask(); |
2303 | |
|
2304 | 0 | ggml_tensor * q = q_cur; |
2305 | 0 | ggml_tensor * k = mctx_cur->get_k(ctx0, il); |
2306 | 0 | ggml_tensor * v = mctx_cur->get_v(ctx0, il); |
2307 | |
|
2308 | 0 | ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, kq_scale, il); |
2309 | 0 | cb(cur, "kqv_out", il); |
2310 | |
|
2311 | 0 | if (v_rot) { |
2312 | 0 | cur = ggml_mul_mat_aux(ctx0, cur, v_rot); |
2313 | 0 | } |
2314 | |
|
2315 | 0 | if (wo) { |
2316 | 0 | cur = build_lora_mm(wo, cur); |
2317 | 0 | } |
2318 | |
|
2319 | 0 | if (wo_b) { |
2320 | | //cb(cur, "kqv_wo", il); |
2321 | 0 | } |
2322 | |
|
2323 | 0 | if (wo_b) { |
2324 | 0 | cur = ggml_add(ctx0, cur, wo_b); |
2325 | 0 | } |
2326 | |
|
2327 | 0 | return cur; |
2328 | 0 | } |
2329 | | |
2330 | 0 | llm_graph_input_attn_cross * llm_graph_context::build_attn_inp_cross() const { |
2331 | 0 | auto inp = std::make_unique<llm_graph_input_attn_cross>(cross); |
2332 | |
|
2333 | 0 | const int32_t n_enc = !cross->v_embd.empty() ? cross->n_enc : hparams.n_ctx_train; |
2334 | |
|
2335 | 0 | inp->cross_kq_mask = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, n_enc, n_tokens, 1, 1); |
2336 | 0 | ggml_set_input(inp->cross_kq_mask); |
2337 | |
|
2338 | 0 | inp->cross_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->cross_kq_mask, GGML_TYPE_F16) : inp->cross_kq_mask; |
2339 | |
|
2340 | 0 | return (llm_graph_input_attn_cross *) res->add_input(std::move(inp)); |
2341 | 0 | } |
2342 | | |
2343 | | ggml_tensor * llm_graph_context::build_attn( |
2344 | | llm_graph_input_attn_cross * inp, |
2345 | | ggml_tensor * wo, |
2346 | | ggml_tensor * wo_b, |
2347 | | ggml_tensor * q_cur, |
2348 | | ggml_tensor * k_cur, |
2349 | | ggml_tensor * v_cur, |
2350 | | ggml_tensor * kq_b, |
2351 | | ggml_tensor * sinks, |
2352 | | ggml_tensor * v_mla, |
2353 | | float kq_scale, |
2354 | 0 | int il) const { |
2355 | | // these nodes are added to the graph together so that they are not reordered |
2356 | | // by doing so, the number of splits in the graph is reduced |
2357 | 0 | ggml_build_forward_expand(gf, q_cur); |
2358 | 0 | ggml_build_forward_expand(gf, k_cur); |
2359 | 0 | ggml_build_forward_expand(gf, v_cur); |
2360 | |
|
2361 | 0 | const auto & kq_mask = inp->get_kq_mask_cross(); |
2362 | |
|
2363 | 0 | ggml_tensor * q = q_cur; |
2364 | 0 | ggml_tensor * k = k_cur; |
2365 | 0 | ggml_tensor * v = v_cur; |
2366 | |
|
2367 | 0 | ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, kq_scale, il); |
2368 | 0 | cb(cur, "kqv_out", il); |
2369 | |
|
2370 | 0 | if (wo) { |
2371 | 0 | cur = build_lora_mm(wo, cur); |
2372 | 0 | } |
2373 | |
|
2374 | 0 | if (wo_b) { |
2375 | | //cb(cur, "kqv_wo", il); |
2376 | 0 | } |
2377 | |
|
2378 | 0 | if (wo_b) { |
2379 | 0 | cur = ggml_add(ctx0, cur, wo_b); |
2380 | 0 | } |
2381 | |
|
2382 | 0 | return cur; |
2383 | 0 | } |
2384 | | |
2385 | | // TODO: maybe separate the inner implementation into a separate function |
2386 | | // like with the non-sliding window equivalent |
2387 | | // once sliding-window hybrid caches are a thing. |
2388 | 0 | llm_graph_input_attn_kv_iswa * llm_graph_context::build_attn_inp_kv_iswa() const { |
2389 | 0 | const auto * mctx_cur = static_cast<const llama_kv_cache_iswa_context *>(mctx); |
2390 | |
|
2391 | 0 | auto inp = std::make_unique<llm_graph_input_attn_kv_iswa>(hparams, cparams, mctx_cur); |
2392 | |
|
2393 | 0 | { |
2394 | 0 | inp->self_k_idxs = mctx_cur->get_base()->build_input_k_idxs(ctx0, ubatch); |
2395 | 0 | inp->self_v_idxs = mctx_cur->get_base()->build_input_v_idxs(ctx0, ubatch); |
2396 | |
|
2397 | 0 | inp->self_kq_mask = build_attn_inp_kq_mask(ctx0, mctx_cur->get_base(), ubatch, cparams); |
2398 | 0 | inp->self_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp->self_kq_mask, GGML_TYPE_F16) : inp->self_kq_mask; |
2399 | 0 | } |
2400 | |
|
2401 | 0 | { |
2402 | 0 | GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE && "Use llama_kv_cache for non-SWA"); |
2403 | |
|
2404 | 0 | inp->self_k_idxs_swa = mctx_cur->get_swa()->build_input_k_idxs(ctx0, ubatch); |
2405 | 0 | inp->self_v_idxs_swa = mctx_cur->get_swa()->build_input_v_idxs(ctx0, ubatch); |
2406 | |
|
2407 | 0 | inp->self_kq_mask_swa = build_attn_inp_kq_mask(ctx0, mctx_cur->get_swa(), ubatch, cparams); |
2408 | 0 | 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; |
2409 | 0 | } |
2410 | |
|
2411 | 0 | inp->self_k_rot = mctx_cur->get_base()->build_input_k_rot(ctx0); |
2412 | 0 | inp->self_v_rot = mctx_cur->get_base()->build_input_v_rot(ctx0); |
2413 | |
|
2414 | 0 | inp->self_k_rot_swa = mctx_cur->get_swa()->build_input_k_rot(ctx0); |
2415 | 0 | inp->self_v_rot_swa = mctx_cur->get_swa()->build_input_v_rot(ctx0); |
2416 | |
|
2417 | 0 | return (llm_graph_input_attn_kv_iswa *) res->add_input(std::move(inp)); |
2418 | 0 | } |
2419 | | |
2420 | | ggml_tensor * llm_graph_context::build_rs( |
2421 | | ggml_tensor * s, |
2422 | | ggml_tensor * state_copy_main, |
2423 | | ggml_tensor * state_copy_extra, |
2424 | | int32_t state_size, |
2425 | | int32_t n_seqs, |
2426 | | uint32_t n_rs, |
2427 | | uint32_t rs_head, |
2428 | | uint32_t rs_size, |
2429 | | int32_t rs_zero, |
2430 | 0 | const llm_graph_get_rows_fn & get_state_rows) const { |
2431 | |
|
2432 | 0 | ggml_tensor * states = ggml_reshape_2d(ctx0, s, state_size, rs_size); |
2433 | | |
2434 | | // Clear a single state which will then be copied to the other cleared states. |
2435 | | // Note that this is a no-op when the view is zero-sized. |
2436 | 0 | ggml_tensor * state_zero = ggml_view_1d(ctx0, states, state_size*(rs_zero >= 0), rs_zero*states->nb[1]*(rs_zero >= 0)); |
2437 | 0 | ggml_build_forward_expand(gf, ggml_scale_inplace(ctx0, state_zero, 0)); |
2438 | | |
2439 | | // copy states |
2440 | | // NOTE: assuming the copy destinations are ALL contained between rs_head and rs_head + n_rs |
2441 | | // {state_size, rs_size} -> {state_size, n_seqs} |
2442 | 0 | ggml_tensor * output_states = get_state_rows(ctx0, states, state_copy_main); |
2443 | 0 | ggml_build_forward_expand(gf, output_states); |
2444 | | |
2445 | | // copy extra states which won't be changed further (between n_seqs and n_rs) |
2446 | 0 | ggml_tensor * states_extra = ggml_get_rows(ctx0, states, state_copy_extra); |
2447 | 0 | ggml_build_forward_expand(gf, |
2448 | 0 | ggml_cpy(ctx0, |
2449 | 0 | states_extra, |
2450 | 0 | ggml_view_2d(ctx0, s, state_size, (n_rs - n_seqs), s->nb[1], (rs_head + n_seqs)*s->nb[1]))); |
2451 | |
|
2452 | 0 | return output_states; |
2453 | 0 | } |
2454 | | |
2455 | | static std::unique_ptr<llm_graph_input_rs> build_rs_inp_impl( |
2456 | | ggml_context * ctx0, |
2457 | | const llama_ubatch & ubatch, |
2458 | 0 | const llama_memory_recurrent_context * mctx_cur) { |
2459 | |
|
2460 | 0 | auto inp = std::make_unique<llm_graph_input_rs>(mctx_cur); |
2461 | |
|
2462 | 0 | const int64_t n_rs = mctx_cur->get_n_rs(); |
2463 | 0 | const int64_t n_seqs = ubatch.n_seqs; |
2464 | |
|
2465 | 0 | inp->s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_rs); |
2466 | 0 | ggml_set_input(inp->s_copy); |
2467 | |
|
2468 | 0 | inp->s_copy_main = ggml_view_1d(ctx0, inp->s_copy, n_seqs, 0); |
2469 | 0 | inp->s_copy_extra = ggml_view_1d(ctx0, inp->s_copy, n_rs - n_seqs, n_seqs * inp->s_copy->nb[0]); |
2470 | |
|
2471 | 0 | inp->head = mctx_cur->get_head(); |
2472 | 0 | inp->rs_z = mctx_cur->get_rs_z(); |
2473 | |
|
2474 | 0 | return inp; |
2475 | 0 | } |
2476 | | |
2477 | 0 | llm_graph_input_rs * llm_graph_context::build_rs_inp() const { |
2478 | 0 | const auto * mctx_cur = static_cast<const llama_memory_recurrent_context *>(mctx); |
2479 | |
|
2480 | 0 | auto inp = build_rs_inp_impl(ctx0, ubatch, mctx_cur); |
2481 | |
|
2482 | 0 | return (llm_graph_input_rs *) res->add_input(std::move(inp)); |
2483 | 0 | } |
2484 | | |
2485 | | ggml_tensor * llm_graph_context::build_rs( |
2486 | | llm_graph_input_rs * inp, |
2487 | | ggml_tensor * s, |
2488 | | int32_t state_size, |
2489 | | int32_t n_seqs, |
2490 | 0 | const llm_graph_get_rows_fn & get_state_rows) const { |
2491 | 0 | const auto * kv_state = inp->mctx; |
2492 | |
|
2493 | 0 | return build_rs(s, inp->s_copy_main, inp->s_copy_extra, state_size, n_seqs, |
2494 | 0 | kv_state->get_n_rs(), kv_state->get_head(), kv_state->get_size(), kv_state->get_rs_z(), |
2495 | 0 | get_state_rows); |
2496 | 0 | } |
2497 | | |
2498 | | ggml_tensor * llm_graph_context::build_rwkv_token_shift_load( |
2499 | | llm_graph_input_rs * inp, |
2500 | | const llama_ubatch & ubatch, |
2501 | 0 | int il) const { |
2502 | 0 | const auto * mctx_cur = static_cast<const llama_memory_recurrent_context *>(mctx); |
2503 | |
|
2504 | 0 | const auto token_shift_count = hparams.token_shift_count; |
2505 | |
|
2506 | 0 | const int64_t n_seqs = ubatch.n_seqs; |
2507 | |
|
2508 | 0 | ggml_tensor * token_shift_all = mctx_cur->get_r_l(il); |
2509 | |
|
2510 | 0 | ggml_tensor * token_shift = build_rs( |
2511 | 0 | inp, token_shift_all, |
2512 | 0 | hparams.n_embd_r(), n_seqs); |
2513 | |
|
2514 | 0 | token_shift = ggml_reshape_3d(ctx0, token_shift, hparams.n_embd, token_shift_count, n_seqs); |
2515 | |
|
2516 | 0 | return token_shift; |
2517 | 0 | } |
2518 | | |
2519 | | ggml_tensor * llm_graph_context::build_rwkv_token_shift_store( |
2520 | | ggml_tensor * token_shift, |
2521 | | const llama_ubatch & ubatch, |
2522 | 0 | int il) const { |
2523 | 0 | const auto * mctx_cur = static_cast<const llama_memory_recurrent_context *>(mctx); |
2524 | |
|
2525 | 0 | const auto token_shift_count = hparams.token_shift_count; |
2526 | 0 | const auto n_embd = hparams.n_embd; |
2527 | |
|
2528 | 0 | const int64_t n_seqs = ubatch.n_seqs; |
2529 | |
|
2530 | 0 | const auto kv_head = mctx_cur->get_head(); |
2531 | |
|
2532 | 0 | return ggml_cpy( |
2533 | 0 | ctx0, |
2534 | 0 | ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * token_shift_count, 0), |
2535 | 0 | 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))) |
2536 | 0 | ); |
2537 | 0 | } |
2538 | | |
2539 | 0 | llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const { |
2540 | 0 | const auto * mctx_cur = static_cast<const llama_memory_hybrid_context *>(mctx); |
2541 | |
|
2542 | 0 | auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr()); |
2543 | 0 | auto inp_attn = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn()); |
2544 | |
|
2545 | 0 | auto inp = std::make_unique<llm_graph_input_mem_hybrid>(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); |
2546 | |
|
2547 | 0 | return (llm_graph_input_mem_hybrid *) res->add_input(std::move(inp)); |
2548 | 0 | } |
2549 | | |
2550 | 0 | llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const { |
2551 | 0 | const auto * mctx_cur = static_cast<const llama_memory_hybrid_context *>(mctx); |
2552 | |
|
2553 | 0 | auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr()); |
2554 | 0 | auto inp_attn = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn()); |
2555 | |
|
2556 | 0 | auto inp = std::make_unique<llm_graph_input_mem_hybrid_k>(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); |
2557 | |
|
2558 | 0 | return (llm_graph_input_mem_hybrid_k *) res->add_input(std::move(inp)); |
2559 | 0 | } |
2560 | | |
2561 | 0 | llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() const { |
2562 | 0 | const auto * mctx_cur = static_cast<const llama_memory_hybrid_iswa_context *>(mctx); |
2563 | |
|
2564 | 0 | auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr()); |
2565 | | |
2566 | | // build iswa attention input |
2567 | 0 | const auto * attn_ctx = mctx_cur->get_attn(); |
2568 | |
|
2569 | 0 | auto inp_attn = std::make_unique<llm_graph_input_attn_kv_iswa>(hparams, cparams, attn_ctx); |
2570 | |
|
2571 | 0 | { |
2572 | 0 | inp_attn->self_k_idxs = attn_ctx->get_base()->build_input_k_idxs(ctx0, ubatch); |
2573 | 0 | inp_attn->self_v_idxs = attn_ctx->get_base()->build_input_v_idxs(ctx0, ubatch); |
2574 | |
|
2575 | 0 | inp_attn->self_kq_mask = build_attn_inp_kq_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); |
2576 | 0 | inp_attn->self_kq_mask_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp_attn->self_kq_mask, GGML_TYPE_F16) : inp_attn->self_kq_mask; |
2577 | 0 | } |
2578 | |
|
2579 | 0 | { |
2580 | 0 | inp_attn->self_k_idxs_swa = attn_ctx->get_swa()->build_input_k_idxs(ctx0, ubatch); |
2581 | 0 | inp_attn->self_v_idxs_swa = attn_ctx->get_swa()->build_input_v_idxs(ctx0, ubatch); |
2582 | |
|
2583 | 0 | inp_attn->self_kq_mask_swa = build_attn_inp_kq_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); |
2584 | 0 | inp_attn->self_kq_mask_swa_cnv = cparams.flash_attn ? ggml_cast(ctx0, inp_attn->self_kq_mask_swa, GGML_TYPE_F16) : inp_attn->self_kq_mask_swa; |
2585 | 0 | } |
2586 | |
|
2587 | 0 | auto inp = std::make_unique<llm_graph_input_mem_hybrid_iswa>(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); |
2588 | |
|
2589 | 0 | return (llm_graph_input_mem_hybrid_iswa *) res->add_input(std::move(inp)); |
2590 | 0 | } |
2591 | | |
2592 | | void llm_graph_context::build_dense_out( |
2593 | | ggml_tensor * dense_2, |
2594 | | ggml_tensor * dense_2_b, |
2595 | 0 | ggml_tensor * dense_3) const { |
2596 | 0 | if (!cparams.embeddings || !(dense_2 || dense_2_b || dense_3)) { |
2597 | 0 | return; |
2598 | 0 | } |
2599 | 0 | ggml_tensor * cur = res->t_embd_pooled != nullptr ? res->t_embd_pooled : res->t_embd; |
2600 | 0 | GGML_ASSERT(cur != nullptr && "missing t_embd_pooled/t_embd"); |
2601 | |
|
2602 | 0 | if (dense_2) { |
2603 | 0 | cur = ggml_mul_mat(ctx0, dense_2, cur); |
2604 | 0 | } |
2605 | 0 | if (dense_2_b) { |
2606 | 0 | cur = ggml_add(ctx0, cur, dense_2_b); |
2607 | 0 | } |
2608 | 0 | if (dense_3) { |
2609 | 0 | cur = ggml_mul_mat(ctx0, dense_3, cur); |
2610 | 0 | } |
2611 | 0 | cb(cur, "result_embd_pooled", -1); |
2612 | 0 | res->t_embd_pooled = cur; |
2613 | 0 | ggml_build_forward_expand(gf, cur); |
2614 | 0 | } |
2615 | | |
2616 | | |
2617 | | void llm_graph_context::build_pooling( |
2618 | | ggml_tensor * cls, |
2619 | | ggml_tensor * cls_b, |
2620 | | ggml_tensor * cls_out, |
2621 | | ggml_tensor * cls_out_b, |
2622 | 0 | ggml_tensor * cls_norm) const { |
2623 | 0 | if (!cparams.embeddings) { |
2624 | 0 | return; |
2625 | 0 | } |
2626 | | |
2627 | 0 | ggml_tensor * inp = res->t_embd; |
2628 | | |
2629 | | //// find result_norm tensor for input |
2630 | | //for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) { |
2631 | | // inp = ggml_graph_node(gf, i); |
2632 | | // if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) { |
2633 | | // break; |
2634 | | // } |
2635 | | |
2636 | | // inp = nullptr; |
2637 | | //} |
2638 | |
|
2639 | 0 | GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor"); |
2640 | |
|
2641 | 0 | ggml_tensor * cur; |
2642 | |
|
2643 | 0 | switch (pooling_type) { |
2644 | 0 | case LLAMA_POOLING_TYPE_NONE: |
2645 | 0 | { |
2646 | 0 | cur = inp; |
2647 | 0 | } break; |
2648 | 0 | case LLAMA_POOLING_TYPE_MEAN: |
2649 | 0 | { |
2650 | 0 | ggml_tensor * inp_mean = build_inp_mean(); |
2651 | 0 | cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean); |
2652 | 0 | } break; |
2653 | 0 | case LLAMA_POOLING_TYPE_CLS: |
2654 | 0 | case LLAMA_POOLING_TYPE_LAST: |
2655 | 0 | { |
2656 | 0 | ggml_tensor * inp_cls = build_inp_cls(); |
2657 | 0 | cur = ggml_get_rows(ctx0, inp, inp_cls); |
2658 | 0 | } break; |
2659 | 0 | case LLAMA_POOLING_TYPE_RANK: |
2660 | 0 | { |
2661 | 0 | if (arch == LLM_ARCH_MODERN_BERT) { |
2662 | | // modern bert gte reranker builds mean first then applies prediction head and classifier |
2663 | | // https://github.com/huggingface/transformers/blob/main/src/transformers/models/modernbert/modular_modernbert.py#L1404-1411 |
2664 | 0 | ggml_tensor * inp_mean = build_inp_mean(); |
2665 | 0 | cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean); |
2666 | 0 | } else { |
2667 | 0 | ggml_tensor * inp_cls = build_inp_cls(); |
2668 | 0 | cur = ggml_get_rows(ctx0, inp, inp_cls); |
2669 | 0 | } |
2670 | | |
2671 | | // classification head |
2672 | | // https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566 |
2673 | 0 | if (cls) { |
2674 | 0 | cur = ggml_mul_mat(ctx0, cls, cur); |
2675 | 0 | if (cls_b) { |
2676 | 0 | cur = ggml_add(ctx0, cur, cls_b); |
2677 | 0 | } |
2678 | 0 | if (arch == LLM_ARCH_MODERN_BERT) { |
2679 | 0 | cur = ggml_gelu(ctx0, cur); |
2680 | 0 | } else { |
2681 | 0 | cur = ggml_tanh(ctx0, cur); |
2682 | 0 | } |
2683 | 0 | if (cls_norm) { |
2684 | | // head norm |
2685 | 0 | cur = build_norm(cur, cls_norm, NULL, LLM_NORM, -1); |
2686 | 0 | } |
2687 | 0 | } |
2688 | | |
2689 | | // some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en |
2690 | | // https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896 |
2691 | | // Single layer classification head (direct projection) |
2692 | | // https://github.com/huggingface/transformers/blob/f4fc42216cd56ab6b68270bf80d811614d8d59e4/src/transformers/models/bert/modeling_bert.py#L1476 |
2693 | 0 | if (cls_out) { |
2694 | 0 | cur = ggml_mul_mat(ctx0, cls_out, cur); |
2695 | 0 | if (cls_out_b) { |
2696 | 0 | cur = ggml_add(ctx0, cur, cls_out_b); |
2697 | 0 | } |
2698 | 0 | } |
2699 | | |
2700 | | // softmax for qwen3 reranker |
2701 | 0 | if (arch == LLM_ARCH_QWEN3 || arch == LLM_ARCH_QWEN3VL) { |
2702 | 0 | cur = ggml_soft_max(ctx0, cur); |
2703 | 0 | } |
2704 | 0 | } break; |
2705 | 0 | default: |
2706 | 0 | { |
2707 | 0 | GGML_ABORT("unknown pooling type"); |
2708 | 0 | } |
2709 | 0 | } |
2710 | | |
2711 | 0 | cb(cur, "result_embd_pooled", -1); |
2712 | 0 | res->t_embd_pooled = cur; |
2713 | |
|
2714 | 0 | ggml_build_forward_expand(gf, cur); |
2715 | 0 | } |
2716 | | |
2717 | 0 | void llm_graph_context::build_sampling() const { |
2718 | 0 | if (samplers.empty() || !res->t_logits) { |
2719 | 0 | return; |
2720 | 0 | } |
2721 | | |
2722 | 0 | std::array<ggml_tensor *, 2> outs; |
2723 | 0 | outs[0] = res->t_logits; |
2724 | |
|
2725 | 0 | auto inp_sampling = std::make_unique<llm_graph_input_sampling>(samplers); |
2726 | 0 | res->add_input(std::move(inp_sampling)); |
2727 | |
|
2728 | 0 | std::map<llama_seq_id, int32_t> seq_to_logit_row; |
2729 | 0 | int32_t logit_row_idx = 0; |
2730 | |
|
2731 | 0 | for (uint32_t i = 0; i < ubatch.n_tokens; i++) { |
2732 | 0 | if (ubatch.output[i]) { |
2733 | 0 | llama_seq_id seq_id = ubatch.seq_id[i][0]; |
2734 | 0 | seq_to_logit_row[seq_id] = logit_row_idx; |
2735 | 0 | logit_row_idx++; |
2736 | 0 | } |
2737 | 0 | } |
2738 | | |
2739 | | // res->t_logits will contain logits for all tokens that want the logits calculated (logits=1 or output=1) |
2740 | 0 | GGML_ASSERT(res->t_logits != nullptr && "missing t_logits tensor"); |
2741 | | |
2742 | | // add a dummy row of logits |
2743 | | // this trick makes the graph static, regardless of which samplers are activated |
2744 | | // this is important in order to minimize graph reallocations |
2745 | 0 | ggml_tensor * logits_t = ggml_pad(ctx0, res->t_logits, 0, 1, 0, 0); |
2746 | |
|
2747 | 0 | for (const auto & [seq_id, sampler] : samplers) { |
2748 | 0 | const auto it = seq_to_logit_row.find(seq_id); |
2749 | | |
2750 | | // inactive samplers always work on the first row |
2751 | 0 | const auto row_idx = it != seq_to_logit_row.end() ? it->second : 0; |
2752 | 0 | const int i_out = it != seq_to_logit_row.end() ? 1 : 0; |
2753 | |
|
2754 | 0 | ggml_tensor * logits_seq = ggml_view_1d(ctx0, logits_t, logits_t->ne[0], row_idx * logits_t->nb[1]); |
2755 | 0 | ggml_format_name(logits_seq, "logits_seq_%d", seq_id); |
2756 | |
|
2757 | 0 | struct llama_sampler_data data = { |
2758 | 0 | /*.logits =*/ logits_seq, |
2759 | 0 | /*.probs =*/ nullptr, |
2760 | 0 | /*.sampled =*/ nullptr, |
2761 | 0 | /*.candidates =*/ nullptr, |
2762 | 0 | }; |
2763 | |
|
2764 | 0 | assert(sampler->iface->backend_apply); |
2765 | 0 | sampler->iface->backend_apply(sampler, ctx0, gf, &data); |
2766 | |
|
2767 | 0 | if (data.sampled != nullptr) { |
2768 | 0 | res->t_sampled[seq_id] = data.sampled; |
2769 | 0 | outs[1] = data.sampled; |
2770 | 0 | ggml_build_forward_select(gf, outs.data(), outs.size(), i_out); |
2771 | 0 | } |
2772 | |
|
2773 | 0 | if (data.probs != nullptr) { |
2774 | 0 | res->t_sampled_probs[seq_id] = data.probs; |
2775 | 0 | outs[1] = data.probs; |
2776 | 0 | ggml_build_forward_select(gf, outs.data(), outs.size(), i_out); |
2777 | 0 | } |
2778 | |
|
2779 | 0 | if (data.logits != nullptr) { |
2780 | 0 | res->t_sampled_logits[seq_id] = data.logits; |
2781 | 0 | outs[1] = data.logits; |
2782 | 0 | ggml_build_forward_select(gf, outs.data(), outs.size(), i_out); |
2783 | 0 | } |
2784 | |
|
2785 | 0 | if (data.candidates != nullptr) { |
2786 | 0 | res->t_candidates[seq_id] = data.candidates; |
2787 | 0 | outs[1] = data.candidates; |
2788 | 0 | ggml_build_forward_select(gf, outs.data(), outs.size(), i_out); |
2789 | 0 | } |
2790 | 0 | } |
2791 | | |
2792 | | // TODO: Call llama_sampler_accept_ggml after all samplers have been applied. |
2793 | | /* |
2794 | | for (const auto & [seq_id, sampler] : samplers) { |
2795 | | if (auto it = res->t_sampled.find(seq_id); it != res->t_sampled.end()) { |
2796 | | ggml_tensor * selected_token = it->second; |
2797 | | if (selected_token != nullptr) { |
2798 | | llama_sampler_accept_ggml(sampler, ctx0, gf, selected_token); |
2799 | | } |
2800 | | } |
2801 | | } |
2802 | | */ |
2803 | 0 | } |
2804 | | |
2805 | 0 | int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) { |
2806 | | // TODO move to hparams if a T5 variant appears that uses a different value |
2807 | 0 | const int64_t max_distance = 128; |
2808 | |
|
2809 | 0 | if (bidirectional) { |
2810 | 0 | n_buckets >>= 1; |
2811 | 0 | } |
2812 | |
|
2813 | 0 | const int64_t max_exact = n_buckets >> 1; |
2814 | |
|
2815 | 0 | int32_t relative_position = x - y; |
2816 | 0 | int32_t relative_bucket = 0; |
2817 | |
|
2818 | 0 | if (bidirectional) { |
2819 | 0 | relative_bucket += (relative_position > 0) * n_buckets; |
2820 | 0 | relative_position = std::abs(relative_position); |
2821 | 0 | } else { |
2822 | 0 | relative_position = -std::min<int32_t>(relative_position, 0); |
2823 | 0 | } |
2824 | |
|
2825 | 0 | 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)); |
2826 | 0 | relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1); |
2827 | 0 | relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large); |
2828 | |
|
2829 | 0 | return relative_bucket; |
2830 | 0 | } |