char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Charlotte Somsupport aliceai_t5_moe98a01afd9

char/aliceai-t5-moe
47.8 KiB1394 linesraw
1#pragma once
2
3#include "llama-arch.h"
4#include "llama-batch.h"
5#include "llama-hparams.h"
6#include "llama-adapter.h"
7
8#include <cstdint>
9#include <cstdlib>
10#include <vector>
11#include <memory>
12#include <set>
13#include <functional>
14#include <map>
15
16struct ggml_cgraph;
17struct ggml_context;
18struct ggml_tensor;
19
20struct llama_cparams;
21struct llama_layer;
22
23struct llama_memory_context_i;
24
25class llama_kv_cache_context;
26class llama_kv_cache_dsa_context;
27class llama_kv_cache_dsa_iswa_context;
28class llama_kv_cache_msa_context;
29class llama_kv_cache_dsv4_raw_context;
30class llama_kv_cache_dsv4_context;
31class llama_kv_cache_iswa_context;
32class llama_memory_recurrent_context;
33class llama_memory_hybrid_context;
34class llama_memory_hybrid_iswa_context;
35
36// certain models (typically multi-modal) can produce different types of graphs
37enum llm_graph_type {
38    LLM_GRAPH_TYPE_DEFAULT,
39    LLM_GRAPH_TYPE_ENCODER,
40    LLM_GRAPH_TYPE_DECODER,
41    LLM_GRAPH_TYPE_DECODER_MTP,
42};
43
44enum llm_fused_op {
45    LLM_FUSED_OP_FLASH_ATTN,
46    LLM_FUSED_OP_GDN_AR,
47    LLM_FUSED_OP_GDN_CH,
48    LLM_FUSED_OP_LIGHTNING_INDEXER,
49    LLM_FUSED_OP_DSV4_HC_PRE,
50    LLM_FUSED_OP_DSV4_HC_COMB,
51    LLM_FUSED_OP_DSV4_HC_POST,
52};
53
54enum llm_ffn_op_type : int {
55    LLM_FFN_NONE = 0,           // sentinel: unset; archs must assign before use
56    LLM_FFN_SILU,
57    LLM_FFN_GELU,
58    LLM_FFN_RELU,
59    LLM_FFN_RELU_SQR,
60    LLM_FFN_SWIGLU,
61    LLM_FFN_GEGLU,
62    LLM_FFN_REGLU,
63    LLM_FFN_SWIGLU_OAI_MOE,
64    LLM_FFN_SITU,           // kimi-k3
65};
66
67enum llm_ffn_gate_type {
68    LLM_FFN_SEQ,
69    LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
70};
71
72enum llm_norm_type {
73    LLM_NORM,
74    LLM_NORM_RMS,
75    LLM_NORM_GROUP,
76};
77
78// TODO: tmp - need something better to pass the data from the encoder to the decoder
79struct llama_cross {
80    // the output embeddings from the encoder as a ggml tensor
81    // TODO: this needs more work to be correct, for now copy the embeddings data to host memory
82    //       ref: https://github.com/ggml-org/llama.cpp/pull/11213#discussion_r1969892524
83    //ggml_tensor * t_embd = nullptr;
84
85    int64_t n_embd = 0;
86    int64_t n_enc  = 0;
87
88    // embeddings data copied to host memory (tmp)
89    std::vector<float> v_embd;
90
91    // needed to construct the cross-attention mask in the decoder
92    std::vector<std::set<llama_seq_id>> seq_ids_enc;
93};
94
95struct llm_graph_params;
96
97//
98// llm_graph_input
99//
100
101class llm_graph_input_i {
102public:
103    llm_graph_input_i() {
104        const char * LLAMA_GRAPH_INPUT_DEBUG = getenv("LLAMA_GRAPH_INPUT_DEBUG");
105        debug = LLAMA_GRAPH_INPUT_DEBUG ? atoi(LLAMA_GRAPH_INPUT_DEBUG) : 0;
106    }
107
108    virtual ~llm_graph_input_i() = default;
109
110    virtual void set_input(const llama_ubatch * ubatch) = 0;
111
112    // return true if the resulting input tensors using the provided graph parameters would be
113    //   the same as the previous input tensors that we have currently stored in the object
114    virtual bool can_reuse(const llm_graph_params & params) {
115        // returning false here by default will prevent from reusing the graph if the check
116        //   for the input type has not been implemented yet
117        GGML_UNUSED(params);
118        return false;
119    }
120protected:
121    // env: LLAMA_GRAPH_INPUT_DEBUG
122    int debug = 0;
123};
124
125using llm_graph_input_ptr = std::unique_ptr<llm_graph_input_i>;
126
127class llm_graph_input_embd : public llm_graph_input_i {
128public:
129    llm_graph_input_embd(int64_t n_embd) : n_embd(n_embd) {}
130    virtual ~llm_graph_input_embd() = default;
131
132    void set_input(const llama_ubatch * ubatch) override;
133
134    bool can_reuse(const llm_graph_params & params) override;
135
136    ggml_tensor * tokens = nullptr; // I32 [n_batch]
137    ggml_tensor * embd   = nullptr; // F32 [n_embd, n_batch]
138
139    const int64_t n_embd = 0;
140};
141
142// similar to llm_graph_input_embd but with an additional hidden state input
143class llm_graph_input_embd_h : public llm_graph_input_i {
144public:
145    llm_graph_input_embd_h(int64_t n_embd) : n_embd(n_embd) {}
146    virtual ~llm_graph_input_embd_h() = default;
147
148    void set_input(const llama_ubatch * ubatch) override;
149
150    bool can_reuse(const llm_graph_params & params) override;
151
152    ggml_tensor * tokens = nullptr; // I32 [n_batch]
153    ggml_tensor * embd   = nullptr; // F32 [n_embd, n_batch]
154    ggml_tensor * h      = nullptr; // F32 [n_embd, n_batch]
155
156    const int64_t n_embd = 0;
157};
158
159class llm_graph_input_pos : public llm_graph_input_i {
160public:
161    llm_graph_input_pos(uint32_t n_pos_per_embd) : n_pos_per_embd(n_pos_per_embd) {}
162    virtual ~llm_graph_input_pos() = default;
163
164    void set_input(const llama_ubatch * ubatch) override;
165
166    bool can_reuse(const llm_graph_params & params) override;
167
168    ggml_tensor * pos = nullptr; // I32 [n_batch]
169
170    const uint32_t n_pos_per_embd = 1;
171};
172
173// temperature tuning, used by llama4
174class llm_graph_input_attn_temp : public llm_graph_input_i {
175public:
176    llm_graph_input_attn_temp(uint32_t n_attn_temp_floor_scale, float f_attn_temp_scale, float f_attn_temp_offset)
177        : n_attn_temp_floor_scale(n_attn_temp_floor_scale), f_attn_temp_scale(f_attn_temp_scale), f_attn_temp_offset(f_attn_temp_offset) {}
178    virtual ~llm_graph_input_attn_temp() = default;
179
180    void set_input(const llama_ubatch * ubatch) override;
181
182    ggml_tensor * attn_scale = nullptr; // F32 [n_batch]
183
184    const uint32_t n_attn_temp_floor_scale;
185    const float    f_attn_temp_scale;
186    const float    f_attn_temp_offset;
187};
188
189class llm_graph_input_pos_bucket : public llm_graph_input_i {
190public:
191    llm_graph_input_pos_bucket(const llama_hparams & hparams) : hparams(hparams) {}
192    virtual ~llm_graph_input_pos_bucket() = default;
193
194    void set_input(const llama_ubatch * ubatch) override;
195
196    ggml_tensor * pos_bucket = nullptr; // I32 [n_batch, n_batch]
197
198    const llama_hparams hparams;
199};
200
201class llm_graph_input_pos_bucket_kv : public llm_graph_input_i {
202public:
203    llm_graph_input_pos_bucket_kv(
204            const llama_hparams & hparams,
205            const llama_kv_cache_context * mctx) : hparams(hparams), mctx(mctx) {}
206    virtual ~llm_graph_input_pos_bucket_kv() = default;
207
208    void set_input(const llama_ubatch * ubatch) override;
209
210    ggml_tensor * pos_bucket = nullptr; // I32 [n_kv, n_batch]
211
212    const llama_hparams hparams;
213
214    const llama_kv_cache_context * mctx;
215};
216
217class llm_graph_input_out_ids : public llm_graph_input_i {
218public:
219    llm_graph_input_out_ids(
220            const llama_hparams & hparams,
221            const llama_cparams & cparams,
222            uint32_t n_outputs) : hparams(hparams), cparams(cparams), n_outputs(n_outputs) {}
223    virtual ~llm_graph_input_out_ids() = default;
224
225    void set_input(const llama_ubatch * ubatch) override;
226
227    bool can_reuse(const llm_graph_params & params) override;
228
229    ggml_tensor * out_ids; // I32 [n_outputs]
230
231    const llama_hparams hparams;
232    const llama_cparams cparams;
233
234    const uint32_t n_outputs;
235};
236
237class llm_graph_input_mean : public llm_graph_input_i {
238public:
239    llm_graph_input_mean(const llama_cparams & cparams) : cparams(cparams) {}
240    virtual ~llm_graph_input_mean() = default;
241
242    void set_input(const llama_ubatch * ubatch) override;
243
244    ggml_tensor * mean; // F32 [n_batch, n_batch]
245
246    const llama_cparams cparams;
247};
248
249class llm_graph_input_cls : public llm_graph_input_i {
250public:
251    llm_graph_input_cls(const llama_cparams & cparams, const llm_arch arch) : cparams(cparams), arch(arch) {}
252    virtual ~llm_graph_input_cls() = default;
253
254    void set_input(const llama_ubatch * ubatch) override;
255
256    ggml_tensor * cls; // I32 [n_batch]
257
258    const llama_cparams cparams;
259    const llm_arch arch;
260};
261
262class llm_graph_input_rs : public llm_graph_input_i {
263public:
264    llm_graph_input_rs(const llama_memory_recurrent_context * mctx) : mctx(mctx) {}
265    virtual ~llm_graph_input_rs() = default;
266
267    void set_input(const llama_ubatch * ubatch) override;
268
269    bool can_reuse(const llm_graph_params & params) override;
270
271    ggml_tensor * s_copy;  // I32 [n_rs]
272
273    // views of s_copy, computed once per graph
274    // and shared across layers which use build_rs
275    ggml_tensor * s_copy_main;   // I32 [n_seqs]
276    ggml_tensor * s_copy_extra;  // I32 [n_rs - n_seqs]
277
278    const llama_memory_recurrent_context * mctx;
279
280    // used in view offsets, need to match for valid graph reuse
281    uint32_t head;
282    int32_t rs_z;
283};
284
285class llm_graph_input_cross_embd : public llm_graph_input_i {
286public:
287    llm_graph_input_cross_embd(
288            const llama_cross * cross) : cross(cross) {}
289    virtual ~llm_graph_input_cross_embd() = default;
290
291    void set_input(const llama_ubatch * ubatch) override;
292
293    bool can_reuse(const llm_graph_params & params) override;
294
295    ggml_tensor * cross_embd; // F32 [n_embd, n_outputs_enc]
296
297    const llama_cross * cross;
298};
299
300class llm_graph_input_attn_no_cache : public llm_graph_input_i {
301public:
302    llm_graph_input_attn_no_cache(const llama_hparams & hparams, const llama_cparams & cparams) :
303        hparams(hparams),
304        cparams(cparams) {
305    }
306    ~llm_graph_input_attn_no_cache() = default;
307
308    void set_input(const llama_ubatch * ubatch) override;
309
310    ggml_tensor * get_kq_mask()     const { return self_kq_mask_cnv; }
311    ggml_tensor * get_kq_mask_swa() const { return self_kq_mask_swa_cnv; }
312
313    // n_tokens == n_batch
314    ggml_tensor * self_kq_mask         = nullptr; // F32/F16 [n_tokens, n_batch/n_stream, 1, n_stream]
315    ggml_tensor * self_kq_mask_cnv     = nullptr; //         [n_tokens, n_batch/n_stream, 1, n_stream]
316    ggml_tensor * self_kq_mask_swa     = nullptr; // F32/F16 [n_tokens, n_batch/n_stream, 1, n_stream]
317    ggml_tensor * self_kq_mask_swa_cnv = nullptr; //         [n_tokens, n_batch/n_stream, 1, n_stream]
318
319    const llama_hparams hparams;
320    const llama_cparams cparams;
321};
322
323class llm_graph_input_attn_kv : public llm_graph_input_i {
324public:
325    llm_graph_input_attn_kv(
326            const llama_hparams & hparams,
327            const llama_cparams & cparams,
328            const llama_kv_cache_context * mctx) :
329        hparams(hparams),
330        cparams(cparams),
331        mctx(mctx) {
332    }
333    ~llm_graph_input_attn_kv() = default;
334
335    void set_input(const llama_ubatch * ubatch) override;
336
337    bool can_reuse(const llm_graph_params & params) override;
338
339    ggml_tensor * get_k_idxs() const { return self_k_idxs; }
340    ggml_tensor * get_v_idxs() const { return self_v_idxs; }
341
342    ggml_tensor * get_kq_mask() const { return self_kq_mask_cnv; }
343
344    ggml_tensor * self_k_idxs = nullptr; // I64 [n_batch]
345    ggml_tensor * self_v_idxs = nullptr; // I64 [n_batch] or [n_batch*n_embd_v_gqa]
346
347    ggml_tensor * self_kq_mask     = nullptr; // F32/F16 [n_kv, n_batch/n_stream, 1, n_stream]
348    ggml_tensor * self_kq_mask_cnv = nullptr; //         [n_kv, n_batch/n_stream, 1, n_stream]
349
350    // note: assumes v_rot^2 == I
351    ggml_tensor * self_k_rot = nullptr;
352    ggml_tensor * self_v_rot = nullptr;
353
354    // note: these have to be copies because in order to be able to reuse a graph, its inputs
355    //       need to carry these parameters with them. otherwise, they can point to freed
356    //       llm_graph_params from a previous batch, causing stack-use-after-return
357    const llama_hparams hparams;
358    const llama_cparams cparams;
359
360    const llama_kv_cache_context * mctx;
361};
362
363// V-less input for the KV cache
364// ref: https://github.com/ggml-org/llama.cpp/pull/19067
365class llm_graph_input_attn_k : public llm_graph_input_i {
366public:
367    llm_graph_input_attn_k(
368            const llama_hparams & hparams,
369            const llama_cparams & cparams,
370            const llama_kv_cache_context * mctx) :
371        hparams(hparams),
372        cparams(cparams),
373        mctx(mctx) {
374    }
375    ~llm_graph_input_attn_k() = default;
376
377    void set_input(const llama_ubatch * ubatch) override;
378
379    bool can_reuse(const llm_graph_params & params) override;
380
381    // like can_reuse, but does not re-bind mctx
382    bool can_reuse_impl(const llm_graph_params & params);
383
384    ggml_tensor * get_k_idxs() const { return self_k_idxs; }
385
386    ggml_tensor * get_kq_mask() const { return self_kq_mask_cnv; }
387
388    ggml_tensor * self_k_idxs = nullptr; // I64 [n_batch]
389
390    ggml_tensor * self_kq_mask     = nullptr; // F32/F16 [n_kv, n_batch/n_stream, 1, n_stream]
391    ggml_tensor * self_kq_mask_cnv = nullptr; //         [n_kv, n_batch/n_stream, 1, n_stream]
392
393    const llama_hparams hparams;
394    const llama_cparams cparams;
395
396    const llama_kv_cache_context * mctx;
397};
398
399class llm_graph_input_attn_k_dsa : public llm_graph_input_i {
400public:
401    llm_graph_input_attn_k_dsa(
402            const llama_hparams & hparams,
403            const llama_cparams & cparams,
404            const llama_kv_cache_dsa_context * mctx) :
405        hparams(hparams),
406        cparams(cparams),
407        mctx(mctx) {
408    }
409    ~llm_graph_input_attn_k_dsa() = default;
410
411    void set_input(const llama_ubatch * ubatch) override;
412
413    bool can_reuse(const llm_graph_params & params) override;
414
415    // like can_reuse, but does not re-bind mctx
416    bool can_reuse_impl(const llm_graph_params & params);
417
418    ggml_tensor * get_k_idxs_mla() const { return self_k_idxs_mla; }
419    ggml_tensor * get_k_idxs_lid() const { return self_k_idxs_lid; }
420
421    ggml_tensor * get_kq_mask_mla() const { return self_kq_mask_mla_cnv; }
422    ggml_tensor * get_kq_mask_lid() const { return self_kq_mask_lid; }
423
424    ggml_tensor * self_k_idxs_mla = nullptr; // I64 [n_batch]
425    ggml_tensor * self_k_idxs_lid = nullptr; // I64 [n_batch]
426
427    ggml_tensor * self_kq_mask_mla     = nullptr; // F32/F16 [n_kv, n_batch/n_stream, 1, n_stream]
428    ggml_tensor * self_kq_mask_mla_cnv = nullptr; //         [n_kv, n_batch/n_stream, 1, n_stream]
429    ggml_tensor * self_kq_mask_lid     = nullptr; // F32     [n_kv, n_batch/n_stream, 1, n_stream]
430    ggml_tensor * self_kq_mask_lid_cnv = nullptr; //         [n_kv, n_batch/n_stream, 1, n_stream]
431
432    ggml_tensor * self_k_rot_lid = nullptr;
433
434    const llama_hparams hparams;
435    const llama_cparams cparams;
436
437    const llama_kv_cache_dsa_context * mctx;
438};
439
440// DSA input (full-attention layers + indexer) with K-only input for the SWA layers
441class llm_graph_input_attn_k_dsa_iswa : public llm_graph_input_i {
442public:
443    llm_graph_input_attn_k_dsa_iswa(
444            std::unique_ptr<llm_graph_input_attn_k_dsa> inp_dsa,
445            std::unique_ptr<llm_graph_input_attn_k>     inp_swa,
446            const llama_kv_cache_dsa_iswa_context *     mctx) :
447        inp_dsa(std::move(inp_dsa)),
448        inp_swa(std::move(inp_swa)),
449        mctx(mctx) {
450    }
451    ~llm_graph_input_attn_k_dsa_iswa() = default;
452
453    void set_input(const llama_ubatch * ubatch) override;
454
455    bool can_reuse(const llm_graph_params & params) override;
456
457    llm_graph_input_attn_k_dsa * get_dsa() const { return inp_dsa.get(); }
458    llm_graph_input_attn_k     * get_swa() const { return inp_swa.get(); }
459
460    std::unique_ptr<llm_graph_input_attn_k_dsa> inp_dsa;
461    std::unique_ptr<llm_graph_input_attn_k>     inp_swa;
462
463    const llama_kv_cache_dsa_iswa_context * mctx;
464};
465
466// standard K/V attention input against the base cache, plus destination indices for the indexer key cache
467class llm_graph_input_attn_kv_msa : public llm_graph_input_attn_kv {
468public:
469    llm_graph_input_attn_kv_msa(
470            const llama_hparams & hparams,
471            const llama_cparams & cparams,
472            const llama_kv_cache_msa_context * mctx);
473    ~llm_graph_input_attn_kv_msa() = default;
474
475    void set_input(const llama_ubatch * ubatch) override;
476
477    bool can_reuse(const llm_graph_params & params) override;
478
479    ggml_tensor * get_k_idxs_idx() const { return self_k_idxs_idx; }
480
481    ggml_tensor * self_k_idxs_idx = nullptr; // I64 [n_batch]
482
483    const llama_kv_cache_msa_context * mctx_msa;
484};
485
486class llm_graph_input_attn_kv_iswa : public llm_graph_input_i {
487public:
488    llm_graph_input_attn_kv_iswa(
489            const llama_hparams & hparams,
490            const llama_cparams & cparams,
491            const llama_kv_cache_iswa_context * mctx) :
492        hparams(hparams),
493        cparams(cparams),
494        mctx(mctx) {
495    }
496    ~llm_graph_input_attn_kv_iswa() = default;
497
498    void set_input(const llama_ubatch * ubatch) override;
499
500    bool can_reuse(const llm_graph_params & params) override;
501
502    ggml_tensor * get_k_idxs()     const { return self_k_idxs; }
503    ggml_tensor * get_v_idxs()     const { return self_v_idxs; }
504    ggml_tensor * get_k_idxs_swa() const { return self_k_idxs_swa; }
505    ggml_tensor * get_v_idxs_swa() const { return self_v_idxs_swa; }
506
507    ggml_tensor * get_kq_mask()     const { return self_kq_mask_cnv; }
508    ggml_tensor * get_kq_mask_swa() const { return self_kq_mask_swa_cnv; }
509
510    ggml_tensor * self_k_idxs     = nullptr; // I64 [n_batch]
511    ggml_tensor * self_v_idxs     = nullptr; // I64 [n_batch] or [n_batch*n_embd_v_gqa]
512    ggml_tensor * self_k_idxs_swa = nullptr; // I64 [n_batch]
513    ggml_tensor * self_v_idxs_swa = nullptr; // I64 [n_batch] or [n_batch*n_embd_v_gqa]
514
515    ggml_tensor * self_kq_mask         = nullptr; // F32/F16 [n_kv, n_batch/n_stream, 1, n_stream]
516    ggml_tensor * self_kq_mask_cnv     = nullptr; //         [n_kv, n_batch/n_stream, 1, n_stream]
517    ggml_tensor * self_kq_mask_swa     = nullptr; // F32/F16 [n_kv, n_batch/n_stream, 1, n_stream]
518    ggml_tensor * self_kq_mask_swa_cnv = nullptr; //         [n_kv, n_batch/n_stream, 1, n_stream]
519
520    ggml_tensor * self_k_rot = nullptr;
521    ggml_tensor * self_v_rot = nullptr;
522
523    ggml_tensor * self_k_rot_swa = nullptr;
524    ggml_tensor * self_v_rot_swa = nullptr;
525
526    const llama_hparams hparams;
527    const llama_cparams cparams;
528
529    const llama_kv_cache_iswa_context * mctx;
530};
531
532class llm_graph_input_attn_k_iswa : public llm_graph_input_i {
533public:
534    llm_graph_input_attn_k_iswa(
535            const llama_hparams & hparams,
536            const llama_cparams & cparams,
537            const llama_kv_cache_iswa_context * mctx) :
538        hparams(hparams),
539        cparams(cparams),
540        mctx(mctx) {
541    }
542    ~llm_graph_input_attn_k_iswa() = default;
543
544    void set_input(const llama_ubatch * ubatch) override;
545
546    bool can_reuse(const llm_graph_params & params) override;
547
548    ggml_tensor * get_k_idxs()     const { return self_k_idxs; }
549    ggml_tensor * get_k_idxs_swa() const { return self_k_idxs_swa; }
550
551    ggml_tensor * get_kq_mask()     const { return self_kq_mask_cnv; }
552    ggml_tensor * get_kq_mask_swa() const { return self_kq_mask_swa_cnv; }
553
554    ggml_tensor * self_k_idxs     = nullptr; // I64 [n_batch]
555    ggml_tensor * self_k_idxs_swa = nullptr; // I64 [n_batch]
556
557    ggml_tensor * self_kq_mask         = nullptr; // F32/F16 [n_kv, n_batch/n_stream, 1, n_stream]
558    ggml_tensor * self_kq_mask_cnv     = nullptr; //         [n_kv, n_batch/n_stream, 1, n_stream]
559    ggml_tensor * self_kq_mask_swa     = nullptr; // F32/F16 [n_kv, n_batch/n_stream, 1, n_stream]
560    ggml_tensor * self_kq_mask_swa_cnv = nullptr; //         [n_kv, n_batch/n_stream, 1, n_stream]
561
562    ggml_tensor * self_k_rot = nullptr;
563    ggml_tensor * self_k_rot_swa = nullptr;
564
565    const llama_hparams hparams;
566    const llama_cparams cparams;
567
568    const llama_kv_cache_iswa_context * mctx;
569};
570
571// DSV4 raw graph inputs are SWA-only, but their mask may be stream-shaped
572// so raw K can be concatenated with DSV4 compressed K in one attention op.
573class llm_graph_input_dsv4_raw {
574public:
575    llm_graph_input_dsv4_raw(
576            const llama_cparams & cparams,
577            const llama_kv_cache_dsv4_raw_context * mctx) :
578        cparams(cparams),
579        mctx(mctx) {
580    }
581
582    void set_input(const llama_ubatch * ubatch);
583
584    ggml_tensor * get_k_idxs() const { return self_k_idxs; }
585    ggml_tensor * get_kq_mask() const { return self_kq_mask_cnv; }
586
587    ggml_tensor * self_k_idxs = nullptr; // I64 [n_batch]
588
589    ggml_tensor * self_kq_mask     = nullptr; // F32/F16 [n_kv, n_batch/n_stream, 1, n_stream]
590    ggml_tensor * self_kq_mask_cnv = nullptr; //         [n_kv, n_batch/n_stream, 1, n_stream]
591
592    ggml_tensor * self_k_rot = nullptr;
593
594    const llama_cparams cparams;
595
596    const llama_kv_cache_dsv4_raw_context * mctx;
597};
598
599class llm_graph_input_dsv4 : public llm_graph_input_i {
600public:
601    struct comp_input {
602        ggml_tensor * state_pos        = nullptr; // I32 [n_state]
603        ggml_tensor * state_persist_src_idxs = nullptr; // I32 [n_state_persist]
604        ggml_tensor * state_persist_dst_idxs = nullptr; // I32 [n_state_persist]
605        ggml_tensor * state_restore_src_idxs = nullptr; // I32 [n_state_restore]
606        ggml_tensor * state_restore_dst_idxs = nullptr; // I32 [n_state_restore]
607        ggml_tensor * state_snapshot_src_idxs = nullptr; // I32 [n_state_snapshot]
608        ggml_tensor * state_snapshot_dst_idxs = nullptr; // I32 [n_state_snapshot]
609        ggml_tensor * state_read_idxs  = nullptr; // I32 [ratio*n_state_write]
610        ggml_tensor * state_write_idxs = nullptr; // I64 [n_state_write]
611        ggml_tensor * state_write_pos  = nullptr; // I32 [n_state_write]
612
613        ggml_tensor * kq_mask    = nullptr; // F32 [n_kv, n_batch/n_stream, 1, n_stream]
614
615        ggml_tensor * k_rot      = nullptr;
616    };
617
618    llm_graph_input_dsv4(
619            const llama_cparams & cparams,
620            std::unique_ptr<llm_graph_input_dsv4_raw> inp_raw,
621            const llama_kv_cache_dsv4_context * mctx) :
622        inp_raw(std::move(inp_raw)),
623        cparams(cparams),
624        mctx(mctx) {
625    }
626    ~llm_graph_input_dsv4() = default;
627
628    void set_input(const llama_ubatch * ubatch) override;
629
630    bool can_reuse(const llm_graph_params & params) override;
631
632    llm_graph_input_dsv4_raw * get_raw() const { return inp_raw.get(); }
633    const comp_input & get_csa() const { return inp_csa; }
634    const comp_input & get_hca() const { return inp_hca; }
635    const comp_input & get_lid() const { return inp_lid; }
636
637    std::unique_ptr<llm_graph_input_dsv4_raw> inp_raw;
638
639    comp_input inp_csa;
640    comp_input inp_hca;
641    comp_input inp_lid;
642
643    const llama_cparams cparams;
644
645    const llama_kv_cache_dsv4_context * mctx;
646};
647
648class llm_graph_input_attn_cross : public llm_graph_input_i {
649public:
650    llm_graph_input_attn_cross(const llama_cross * cross) : cross(cross) {}
651    ~llm_graph_input_attn_cross() = default;
652
653    void set_input(const llama_ubatch * ubatch) override;
654
655    bool can_reuse(const llm_graph_params & params) override;
656
657    ggml_tensor * get_kq_mask_cross() const { return cross_kq_mask_cnv; }
658
659    ggml_tensor * cross_kq_mask     = nullptr; // F32/F16 [n_outputs_enc, n_batch, 1, 1]
660    ggml_tensor * cross_kq_mask_cnv = nullptr; // F32/F16 [n_outputs_enc, n_batch, 1, 1]
661
662    const llama_cross * cross = nullptr;
663};
664
665class llm_graph_input_mem_hybrid : public llm_graph_input_i {
666public:
667    llm_graph_input_mem_hybrid(
668            const llama_cparams & cparams,
669            std::unique_ptr<llm_graph_input_attn_kv> inp_attn,
670            std::unique_ptr<llm_graph_input_rs>      inp_rs,
671            const llama_memory_hybrid_context *      mctx) :
672        inp_attn(std::move(inp_attn)),
673        inp_rs(std::move(inp_rs)),
674        cparams(cparams),
675        mctx(mctx) { }
676    virtual ~llm_graph_input_mem_hybrid() = default;
677
678    void set_input(const llama_ubatch * ubatch) override;
679
680    bool can_reuse(const llm_graph_params & params) override;
681
682    std::unique_ptr<llm_graph_input_attn_kv> inp_attn;
683    std::unique_ptr<llm_graph_input_rs>      inp_rs;
684
685    llm_graph_input_attn_kv * get_attn() const { return inp_attn.get(); }
686    llm_graph_input_rs      * get_recr() const { return inp_rs.get(); }
687
688    const llama_cparams cparams;
689
690    const llama_memory_hybrid_context * mctx;
691};
692
693class llm_graph_input_mem_hybrid_k : public llm_graph_input_i {
694public:
695    llm_graph_input_mem_hybrid_k(
696            const llama_cparams & cparams,
697            std::unique_ptr<llm_graph_input_attn_k> inp_attn,
698            std::unique_ptr<llm_graph_input_rs>      inp_rs,
699            const llama_memory_hybrid_context *      mctx) :
700        inp_attn(std::move(inp_attn)),
701        inp_rs(std::move(inp_rs)),
702        cparams(cparams),
703        mctx(mctx) { }
704    virtual ~llm_graph_input_mem_hybrid_k() = default;
705
706    void set_input(const llama_ubatch * ubatch) override;
707
708    bool can_reuse(const llm_graph_params & params) override;
709
710    std::unique_ptr<llm_graph_input_attn_k> inp_attn;
711    std::unique_ptr<llm_graph_input_rs>      inp_rs;
712
713    llm_graph_input_attn_k * get_attn() const { return inp_attn.get(); }
714    llm_graph_input_rs      * get_recr() const { return inp_rs.get(); }
715
716    const llama_cparams cparams;
717
718    const llama_memory_hybrid_context * mctx;
719};
720
721class llm_graph_input_mem_hybrid_iswa : public llm_graph_input_i {
722public:
723    llm_graph_input_mem_hybrid_iswa(
724            const llama_cparams & cparams,
725            std::unique_ptr<llm_graph_input_attn_kv_iswa> inp_attn,
726            std::unique_ptr<llm_graph_input_rs>          inp_rs,
727            const llama_memory_hybrid_iswa_context *     mctx) :
728        inp_attn(std::move(inp_attn)),
729        inp_rs(std::move(inp_rs)),
730        cparams(cparams),
731        mctx(mctx) { }
732    virtual ~llm_graph_input_mem_hybrid_iswa() = default;
733
734    void set_input(const llama_ubatch * ubatch) override;
735
736    bool can_reuse(const llm_graph_params & params) override;
737
738    std::unique_ptr<llm_graph_input_attn_kv_iswa> inp_attn;
739    std::unique_ptr<llm_graph_input_rs>          inp_rs;
740
741    llm_graph_input_attn_kv_iswa * get_attn() const { return inp_attn.get(); }
742    llm_graph_input_rs           * get_recr() const { return inp_rs.get(); }
743
744    const llama_cparams cparams;
745
746    const llama_memory_hybrid_iswa_context * mctx;
747};
748
749class llm_graph_input_sampling : public llm_graph_input_i {
750public:
751    llm_graph_input_sampling(std::map<llama_seq_id, llama_sampler *> samplers) :
752        samplers(std::move(samplers)) { }
753    virtual ~llm_graph_input_sampling() = default;
754
755    void set_input(const llama_ubatch * ubatch) override;
756    bool can_reuse(const llm_graph_params & params) override;
757
758    std::map<llama_seq_id, llama_sampler *> samplers;
759};
760
761//
762// llm_graph_result
763//
764
765// these objects deliver the result from the graph build process back to the llama_context
766// note that the input tensors created for the graph are referenced here - the goal is to be able to populate their
767//   specific data, by calling the set_inputs() method
768// along with the input tensors, the object also provides commonly used outputs tensors, such as logits, embeddings, etc.
769//   these are used by the llama_context to extact the relevant data, based on the compute parameters
770
771// callback that allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
772using llm_graph_cb = std::function<void(const llama_ubatch & ubatch, ggml_tensor * cur, const char * name, int il)>;
773
774class llm_graph_result;
775
776struct llm_graph_params {
777    llm_arch arch = LLM_ARCH_UNKNOWN;
778
779    llama_hparams hparams;
780    llama_cparams cparams;
781
782    llama_ubatch ubatch; // note: intentionally make a copy
783
784    llm_graph_type gtype;
785
786    ggml_backend_sched_t sched;
787    ggml_backend_t backend_cpu;
788
789    const llama_adapter_cvec     * cvec;
790    const llama_adapter_loras    * loras;
791    const llama_memory_context_i * mctx;
792    const llama_cross            * cross;
793
794    std::map<llama_seq_id, llama_sampler *> samplers;
795
796    static bool samplers_equal(
797          const std::map<llama_seq_id, llama_sampler *> & lhs,
798          const std::map<llama_seq_id, llama_sampler *> & rhs) {
799        if (lhs.size() != rhs.size()) {
800            return false;
801        }
802        for (const auto & [seq_id, sampler] : lhs) {
803            auto it = rhs.find(seq_id);
804            if (it == rhs.end() || it->second != sampler) {
805                return false;
806            }
807        }
808        return true;
809    }
810
811    uint32_t n_outputs;
812
813    llm_graph_cb cb;
814
815    llm_graph_result * res;
816
817    // return true if the "other" params would result in a graph with the same topology as with the current params
818    //   having the same topology allows us to reuse the graph in some cases
819    bool allow_reuse(const llm_graph_params & other) const {
820        // first check the ubatch
821        bool can_reuse_ubatch =
822            ubatch.equal_seqs() == other.ubatch.equal_seqs() &&
823            ubatch.n_tokens     == other.ubatch.n_tokens &&
824            ubatch.n_seq_tokens == other.ubatch.n_seq_tokens &&
825            ubatch.n_seqs       == other.ubatch.n_seqs &&
826            ubatch.n_seqs_unq   == other.ubatch.n_seqs_unq &&
827            (
828                (!ubatch.token && !other.ubatch.token) ||
829                (!ubatch.embd  && !other.ubatch.embd)  ||
830                (ubatch.token && other.ubatch.token && ubatch.embd && other.ubatch.embd)
831            );
832
833        // when we split the batch using "equal_seqs" we have to verify that the participating sequences are the same
834        //   the reason is because the set of attention streams would be different for different sequences
835        if (can_reuse_ubatch && ubatch.equal_seqs()) {
836            if (!ubatch.data) {
837                // if the old ubatch does not own it's data, then we cannot guarantee that it is still alive, and
838                //   therefore we cannot perform the sequence id check. normally should never happen
839                can_reuse_ubatch = false;
840            } else {
841                for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
842                    can_reuse_ubatch &= ubatch.seq_id_unq[s] == other.ubatch.seq_id_unq[s];
843                }
844            }
845        }
846
847        if (!can_reuse_ubatch) {
848            return false;
849        }
850
851        if (n_outputs != other.n_outputs) {
852            return false;
853        }
854
855        if (!samplers_equal(samplers, other.samplers)) {
856            return false;
857        }
858
859        if (samplers.size() > 0) {
860            if (!ubatch.data || !other.ubatch.data) {
861                return false;
862            }
863
864            // check that the outputs are the same for all samplers
865            for (uint32_t i = 0; i < ubatch.n_tokens; ++i) {
866                if (ubatch.output[i]    != other.ubatch.output[i] ||
867                    ubatch.seq_id[i][0] != other.ubatch.seq_id[i][0]) {
868                    return false;
869                }
870            }
871        }
872
873        // TODO: https://github.com/ggml-org/llama.cpp/pull/24340#discussion_r3448035248
874        if (cparams.nextn_layer_offset != other.cparams.nextn_layer_offset) {
875            return false;
876        }
877
878        return
879            cparams.embeddings              == other.cparams.embeddings              &&
880            cparams.embeddings_nextn        == other.cparams.embeddings_nextn        &&
881            cparams.embeddings_nextn_masked == other.cparams.embeddings_nextn_masked &&
882            cparams.causal_attn             == other.cparams.causal_attn             &&
883            arch  == other.arch  &&
884            gtype == other.gtype &&
885            cvec  == other.cvec  &&
886            loras == other.loras &&
887            cross == other.cross;
888    }
889};
890
891struct llm_graph_fused_node {
892    llm_fused_op op;
893    ggml_tensor * tensor;
894    int il;
895};
896
897class llm_graph_result {
898public:
899    llm_graph_result(int64_t max_nodes);
900
901    virtual ~llm_graph_result() = default;
902
903    ggml_tensor * get_inp_tokens()  const { return t_inp_tokens; }
904    ggml_tensor * get_logits()      const { return t_logits; }
905    ggml_tensor * get_embd()        const { return t_embd; }
906    ggml_tensor * get_embd_pooled() const { return t_embd_pooled; }
907    ggml_tensor * get_h_nextn()     const { return t_h_nextn; }
908
909    ggml_tensor * get_layer_inp(int il) const { return t_layer_inp[il]; }
910
911    ggml_cgraph  * get_gf()  const { return gf; }
912    ggml_context * get_ctx() const { return ctx_compute.get(); }
913
914    int64_t get_max_nodes() const;
915
916    void reset();
917
918    void set_inputs(const llama_ubatch * ubatch);
919    void set_outputs(const llm_graph_params & params);
920
921    // try to update the existing graph result using the new graph parameters in order to reuse it
922    // this can only be done if we determine that the resulting graph using the new graph parameters
923    //   would be identical to the existing graph. in that case, we simply have to update the memory
924    //   contexts of the input tensors of the graph and we can reuse it for another computation
925    // return true if the graph was updated and can be reused
926    bool can_reuse(const llm_graph_params & params);
927
928    llm_graph_input_i * add_input(llm_graph_input_ptr input);
929
930    void add_fused_node(llm_graph_fused_node result);
931
932    const std::vector<llm_graph_fused_node> & get_fused_nodes() const { return fused_nodes; }
933
934    void set_params(const llm_graph_params & params);
935
936    // important graph nodes
937    ggml_tensor * t_inp_tokens  = nullptr;
938    ggml_tensor * t_inp_embd    = nullptr; // [n_embd_inp, n_tokens]
939    ggml_tensor * t_logits      = nullptr;
940    ggml_tensor * t_embd        = nullptr;
941    ggml_tensor * t_embd_pooled = nullptr;
942    ggml_tensor * t_h_nextn     = nullptr; // [n_embd, n_outputs] hidden state before final output norm
943
944    std::vector<ggml_tensor *> t_layer_inp;
945
946    std::vector<ggml_tensor *> t_sampled;
947    std::vector<ggml_tensor *> t_sampled_probs;
948    std::vector<ggml_tensor *> t_sampled_logits;
949    std::vector<ggml_tensor *> t_candidates;
950
951    std::vector<llm_graph_input_ptr> inputs;
952    std::vector<llm_graph_fused_node> fused_nodes;
953
954    ggml_context_ptr ctx_compute;
955
956    // memory buffers used to evaluate the model
957    std::vector<uint8_t> buf_compute_meta;
958
959    ggml_cgraph * gf;
960
961    int64_t max_nodes;
962
963private:
964    // keep a copy of the previous graph parameters
965    // we will use this to determine whether the graph can be reused by comparing them with the new parameters
966    // note: these are updated after constructing the new graph
967    llm_graph_params params;
968
969    // env: LLAMA_GRAPH_RESULT_DEBUG
970    int debug = 0;
971};
972
973using llm_graph_result_ptr = std::unique_ptr<llm_graph_result>;
974
975//
976// llm_graph_context
977//
978
979// used in build_rs to properly order writes and avoid unnecessary copies
980using llm_graph_get_rows_fn = std::function<ggml_tensor * (ggml_context *, ggml_tensor * states, ggml_tensor * ids)>;
981
982struct llm_graph_qkv {
983    ggml_tensor * q; // [n_embd_head, n_head,    n_tokens]
984    ggml_tensor * k; // [n_embd_head, n_head_kv, n_tokens]
985    ggml_tensor * v; // [n_embd_head, n_head_kv, n_tokens]
986};
987
988struct llm_graph_context {
989    const llm_arch arch;
990
991    const llama_hparams & hparams;
992    const llama_cparams & cparams;
993    const llama_ubatch  & ubatch;
994
995    const int64_t n_embd;
996    const int64_t n_layer;
997    const int64_t n_layer_nextn;
998    const int64_t n_rot;
999    const int64_t n_ctx;       // user-specified context size (can be different from n_ctx_train)
1000    const int64_t n_head;
1001    const int64_t n_head_kv;
1002    const int64_t n_embd_head_k;
1003    const int64_t n_embd_k_gqa;
1004    const int64_t n_embd_head_v;
1005    const int64_t n_embd_v_gqa;
1006    const int64_t n_expert;
1007    const int64_t n_expert_used;
1008
1009    const float freq_base;
1010    const float freq_scale;
1011    const float ext_factor;
1012    const float attn_factor;
1013    const float beta_fast;
1014    const float beta_slow;
1015    const float norm_eps;
1016    const float norm_rms_eps;
1017
1018    const int64_t n_tokens;
1019    const int64_t n_outputs;
1020    const int32_t n_ctx_orig; // yarn
1021
1022    const enum llama_pooling_type pooling_type;
1023    const enum llama_rope_type    rope_type;
1024
1025    ggml_backend_sched_t sched;
1026
1027    ggml_backend_t backend_cpu; // TODO: needed by build_attn_mha, figure out a way to remove?
1028
1029    const llama_adapter_cvec     * cvec;
1030    const llama_adapter_loras    * loras;
1031    const llama_memory_context_i * mctx;
1032    const llama_cross            * cross;
1033
1034    std::map<llama_seq_id, llama_sampler *> samplers;
1035
1036    const llm_graph_cb & cb_func;
1037
1038    llm_graph_result * res;
1039
1040    ggml_context * ctx0 = nullptr;
1041    ggml_cgraph  * gf   = nullptr;
1042
1043    llm_graph_context(const llm_graph_params & params);
1044    virtual ~llm_graph_context() = default;
1045
1046    void cb(ggml_tensor * cur, const char * name, int il) const;
1047
1048    //
1049    // common
1050    //
1051
1052    ggml_tensor * build_cvec(
1053             ggml_tensor * cur,
1054                     int   il) const;
1055
1056    // do mat_mul, while optionally apply lora and per-tensor scale
1057    ggml_tensor * build_lora_mm(
1058              ggml_tensor * w,
1059              ggml_tensor * cur,
1060              ggml_tensor * w_s = nullptr) const;
1061
1062    // do mat_mul_id, while optionally apply lora and per-expert scale
1063    ggml_tensor * build_lora_mm_id(
1064              ggml_tensor * w,   // ggml_tensor * as
1065              ggml_tensor * cur, // ggml_tensor * b
1066              ggml_tensor * ids,
1067              ggml_tensor * w_s = nullptr) const;
1068
1069    ggml_tensor * build_norm(
1070             ggml_tensor * cur,
1071             ggml_tensor * mw,
1072             ggml_tensor * mb,
1073           llm_norm_type   type,
1074                     int   il) const;
1075
1076
1077    // compute Q, K, V projections with optional bias and reshape
1078    // supports both fused wqkv and separate wq/wk/wv paths
1079    llm_graph_qkv build_qkv(
1080        const llama_layer & layer,
1081              ggml_tensor * cur,
1082                  int64_t   n_embd_head,
1083                  int64_t   n_head,
1084                  int64_t   n_head_kv,
1085                      int   il) const;
1086
1087    // Set reshape to false to return contiguous projections before clamp/reshape.
1088    llm_graph_qkv build_qkv(
1089        const llama_layer & layer,
1090              ggml_tensor * cur,
1091                  int64_t   n_embd_head_q,
1092                  int64_t   n_head_q,
1093                  int64_t   n_embd_head_k,
1094                  int64_t   n_head_k,
1095                  int64_t   n_embd_head_v,
1096                  int64_t   n_head_v,
1097                      int   il,
1098                     bool   reshape = true) const;
1099
1100    ggml_tensor * build_ffn(
1101             ggml_tensor * cur,
1102             ggml_tensor * up,
1103             ggml_tensor * up_b,
1104             ggml_tensor * up_s,
1105             ggml_tensor * gate,
1106             ggml_tensor * gate_b,
1107             ggml_tensor * gate_s,
1108             ggml_tensor * down,
1109             ggml_tensor * down_b,
1110             ggml_tensor * down_s,
1111             ggml_tensor * act_scales,
1112         llm_ffn_op_type   type_op,
1113       llm_ffn_gate_type   type_gate,
1114                     int   il) const;
1115
1116    // build MoE FFN without bias tensors
1117    ggml_tensor * build_moe_ffn(
1118             ggml_tensor * cur,
1119             ggml_tensor * gate_inp,
1120             ggml_tensor * up_exps,
1121             ggml_tensor * gate_exps,
1122             ggml_tensor * down_exps,
1123             ggml_tensor * exp_probs_b,
1124                 int64_t   n_expert,
1125                 int64_t   n_expert_used,
1126         llm_ffn_op_type   type_op,
1127                    bool   norm_w,
1128                   float   w_scale,
1129            llama_expert_gating_func_type gating_op,
1130                     int   il,
1131             ggml_tensor * probs_in = nullptr,
1132             ggml_tensor * gate_up_exps = nullptr,
1133             ggml_tensor * up_exps_s = nullptr,
1134             ggml_tensor * gate_exps_s = nullptr,
1135             ggml_tensor * down_exps_s = nullptr,
1136             ggml_tensor * selected_experts_in = nullptr) const;
1137
1138    ggml_tensor * build_moe_ffn(
1139             ggml_tensor * cur,
1140             ggml_tensor * gate_inp,
1141             ggml_tensor * gate_inp_b,
1142             ggml_tensor * up_exps,
1143             ggml_tensor * up_exps_b,
1144             ggml_tensor * gate_exps,
1145             ggml_tensor * gate_exps_b,
1146             ggml_tensor * down_exps,
1147             ggml_tensor * down_exps_b,
1148             ggml_tensor * exp_probs_b,
1149                 int64_t   n_expert,
1150                 int64_t   n_expert_used,
1151         llm_ffn_op_type   type_op,
1152                    bool   norm_w,
1153                   float   w_scale,
1154            llama_expert_gating_func_type gating_op,
1155                     int   il,
1156             ggml_tensor * probs_in = nullptr,
1157             ggml_tensor * gate_up_exps = nullptr,
1158             ggml_tensor * gate_up_exps_b = nullptr,
1159             ggml_tensor * up_exps_s = nullptr,
1160             ggml_tensor * gate_exps_s = nullptr,
1161             ggml_tensor * down_exps_s = nullptr,
1162             ggml_tensor * selected_experts_in = nullptr) const;
1163
1164    //
1165    // inputs
1166    //
1167
1168    ggml_tensor * build_inp_embd(ggml_tensor * tok_embd) const;
1169    ggml_tensor * build_inp_pos() const;
1170    ggml_tensor * build_inp_attn_scale() const;
1171    ggml_tensor * build_inp_out_ids() const;
1172    ggml_tensor * build_inp_mean() const;
1173    ggml_tensor * build_inp_cls() const;
1174
1175    ggml_tensor * build_inp_cross_embd() const;
1176    ggml_tensor * build_inp_pos_bucket_enc() const;
1177    ggml_tensor * build_inp_pos_bucket_dec() const;
1178    ggml_tensor * build_pos_bias(ggml_tensor * pos_bucket, ggml_tensor * attn_rel_b) const;
1179
1180    //
1181    // attention
1182    //
1183
1184    ggml_tensor * build_attn_mha(
1185            ggml_tensor * q,       // [n_embd_head_q, n_head_q, n_tokens]
1186            ggml_tensor * k,       // [n_embd_head_k, n_head_k, n_tokens]
1187            ggml_tensor * v,       // [n_embd_head_v, n_head_v, n_tokens] (v_trans = false)
1188            ggml_tensor * kq_b,
1189            ggml_tensor * kq_mask,
1190            ggml_tensor * sinks,   // [n_head_q]
1191            ggml_tensor * v_mla,   // [n_embd_head_v_mla, n_embd_head_v, n_head_v]
1192                int64_t   n_kv_max,
1193                  float   kq_scale,
1194                    int   il) const;
1195
1196    llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const;
1197
1198    ggml_tensor * build_attn(
1199            llm_graph_input_attn_no_cache * inp,
1200            ggml_tensor * wo,
1201            ggml_tensor * wo_b,
1202            ggml_tensor * wo_s,
1203            ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
1204            ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
1205            ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
1206            ggml_tensor * kq_b,
1207            ggml_tensor * sinks, // [n_head_q]
1208            ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v]
1209                  float   kq_scale,
1210                    int   il) const;
1211
1212    llm_graph_input_attn_kv * build_attn_inp_kv() const;
1213
1214    ggml_tensor * build_attn(
1215            llm_graph_input_attn_kv * inp,
1216            ggml_tensor * wo,
1217            ggml_tensor * wo_b,
1218            ggml_tensor * wo_s,
1219            ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
1220            ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
1221            ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
1222            ggml_tensor * kq_b,
1223            ggml_tensor * sinks, // [n_head_q]
1224            ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] // TODO: remove
1225                  float   kq_scale,
1226                    int   il) const;
1227
1228    llm_graph_input_attn_k  * build_attn_inp_k() const;
1229
1230    ggml_tensor * build_attn(
1231            llm_graph_input_attn_k * inp,
1232            ggml_tensor * wo,
1233            ggml_tensor * wo_b,
1234            ggml_tensor * wo_s,
1235            ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
1236            ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
1237            ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
1238            ggml_tensor * kq_b,
1239            ggml_tensor * sinks, // [n_head_q]
1240            ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v]
1241                  float   kq_scale,
1242                    int   il) const;
1243
1244    llm_graph_input_attn_k_dsa * build_attn_inp_k_dsa() const;
1245
1246    llm_graph_input_attn_k_dsa_iswa * build_attn_inp_k_dsa_iswa() const;
1247
1248    llm_graph_input_attn_kv_msa * build_attn_inp_kv_msa(bool msa_enabled) const;
1249
1250    ggml_tensor * build_attn(
1251            llm_graph_input_attn_k_dsa * inp,
1252            ggml_tensor * wo,
1253            ggml_tensor * wo_b,
1254            ggml_tensor * wo_s,
1255            ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
1256            ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
1257            ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
1258            ggml_tensor * kq_b,
1259            ggml_tensor * sinks, // [n_head_q]
1260            ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v]
1261            ggml_tensor * top_k, // [n_indexer_top_k, n_tokens]
1262                  float   kq_scale,
1263                    int   il) const;
1264
1265    llm_graph_input_attn_kv_iswa * build_attn_inp_kv_iswa() const;
1266
1267    llm_graph_input_dsv4 * build_inp_dsv4() const;
1268
1269    // note: if k_cur or v_cur are not provided, they will not be stored in the memory
1270    ggml_tensor * build_attn(
1271            llm_graph_input_attn_kv_iswa * inp,
1272            ggml_tensor * wo,
1273            ggml_tensor * wo_b,
1274            ggml_tensor * wo_s,
1275            ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
1276            ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] optional
1277            ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] optional
1278            ggml_tensor * kq_b,
1279            ggml_tensor * sinks, // [n_head_q]
1280            ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v]
1281                  float   kq_scale,
1282                    int   il) const;
1283
1284    llm_graph_input_attn_k_iswa * build_attn_inp_k_iswa() const;
1285
1286    // note: if k_cur is not provided, it will not be stored in the memory
1287    // note: the K cache is used as V (MLA-style attention)
1288    ggml_tensor * build_attn(
1289            llm_graph_input_attn_k_iswa * inp,
1290            ggml_tensor * wo,
1291            ggml_tensor * wo_b,
1292            ggml_tensor * wo_s,
1293            ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
1294            ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] optional
1295            ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] optional
1296            ggml_tensor * kq_b,
1297            ggml_tensor * sinks, // [n_head_q]
1298            ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v]
1299                  float   kq_scale,
1300                    int   il) const;
1301
1302    llm_graph_input_attn_cross * build_attn_inp_cross() const;
1303
1304    ggml_tensor * build_attn(
1305            llm_graph_input_attn_cross * inp,
1306            ggml_tensor * wo,
1307            ggml_tensor * wo_b,
1308            ggml_tensor * wo_s,
1309            ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
1310            ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
1311            ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
1312            ggml_tensor * kq_b,
1313            ggml_tensor * sinks, // [n_head_q]
1314            ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v]
1315                  float   kq_scale,
1316                    int   il) const;
1317
1318    //
1319    // recurrent
1320    //
1321
1322    // TODO: move this implementation to llama_memory_recurrent.
1323    //       this is analogous to llama_kv_cache::cpy_k / cpy_v
1324    //       when moving, avoid passing `ggml_cgraph` - only pass `ggml_context`. would likely need to split the
1325    //         implementation in 2 separate methods. the goal is to avoid calling `ggml_build_forward_expand` in
1326    //         `llama_memory_recurrent`
1327    ggml_tensor * build_rs(
1328            ggml_tensor * s,
1329            ggml_tensor * state_copy_main,
1330            ggml_tensor * state_copy_extra,
1331                int32_t   state_size,
1332                int32_t   n_seqs,
1333               uint32_t   n_rs,
1334               uint32_t   rs_head,
1335               uint32_t   rs_size,
1336                int32_t   rs_zero,
1337            const llm_graph_get_rows_fn & get_state_rows = ggml_get_rows) const;
1338
1339    llm_graph_input_rs * build_rs_inp() const;
1340
1341    ggml_tensor * build_rs(
1342            llm_graph_input_rs * inp,
1343            ggml_tensor * s,
1344                int32_t   state_size,
1345                int32_t   n_seqs,
1346            const llm_graph_get_rows_fn & get_state_rows = ggml_get_rows) const;
1347
1348    ggml_tensor * build_rwkv_token_shift_load(
1349        llm_graph_input_rs * inp,
1350        const llama_ubatch & ubatch,
1351                       int   il) const;
1352
1353    ggml_tensor * build_rwkv_token_shift_store(
1354             ggml_tensor * token_shift,
1355      const llama_ubatch & ubatch,
1356                     int   il) const;
1357    //
1358    // hybrid
1359    //
1360
1361    llm_graph_input_mem_hybrid * build_inp_mem_hybrid() const;
1362    llm_graph_input_mem_hybrid_k * build_inp_mem_hybrid_k() const;
1363
1364    llm_graph_input_mem_hybrid_iswa * build_inp_mem_hybrid_iswa() const;
1365
1366    //
1367    // pooling
1368    //
1369
1370    void build_pooling(
1371            ggml_tensor * cls,
1372            ggml_tensor * cls_b,
1373            ggml_tensor * cls_out,
1374            ggml_tensor * cls_out_b,
1375            ggml_tensor * cls_norm) const;
1376
1377    //
1378    // sampling (backend sampling)
1379    //
1380
1381    void build_sampling() const;
1382
1383    //
1384    // dense (out)
1385    //
1386
1387    void build_dense_out(
1388            ggml_tensor * dense_2,
1389            ggml_tensor * dense_2_b,
1390            ggml_tensor * dense_3) const;
1391};
1392
1393// TODO: better name
1394int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional);