Coverage Report

Created: 2026-01-09 06:17

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