okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-1b (033cfdd8c) into f-own-int: nothing downloads llama.cppb2de2641f

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