Coverage Report

Created: 2026-03-03 06:12

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