Coverage Report

Created: 2025-12-14 06:23

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