Coverage Report

Created: 2026-07-16 06:35

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