transcribe-cpp-sys 0.5.0

Native FFI bindings for transcribe.cpp, a C/C++ speech-to-text library built on ggml
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
#pragma once

#include "ggml-backend-impl.h"
#include "ggml-backend.h"
#include "ggml.h"
#include "openvino/decoder.h"

#include <cstdint>
#include <cstring>
#include <map>
#include <memory>
#include <openvino/core/partial_shape.hpp>
#include <openvino/runtime/tensor.hpp>
#include <optional>
#include <set>
#include <string>
#include <utility>
#include <vector>

struct ModelParams {
    int ctx = -1;
    int ctx_per_seq = -1;
    int ctx_per_seq_swa = -1;
    int n_seq = 1;
    int n_heads_kv = -1;
    // Per-layer KV head count. gemma-4 12B interleaves 8 x 256 sliding layers with 1 x 512
    // full-attention layers, so no single scalar describes every layer. Keyed by layer, not by
    // layer TYPE, because the SWA classification depends on the context size (extents tie at a
    // small -c) while the head count does not.
    std::map<int, int> n_heads_kv_per_layer;
    int head_size = -1;
    int state_size = -1;  // for SSM molels, eg qwen35
    int32_t rope_params[16] = {};
    int n_rs_slots = -1;
    bool has_rs_rollback = false;
    bool mixed_rope_params = false;
    bool is_cacheless_attn = false;
    // the graph writes a transposed V cache (`-fa off`: one value element per row, tokens along the row)
    bool v_trans = false;
    // the graph has FLASH_ATTN_EXT with logit soft-capping (gemma-2)
    bool softcap_attn = false;
    std::vector<int> swa_layers;
    // The sliding-window mask tensor, identified in compute_llm_params() by grouping attention
    // layers on the mask they consume. Only used to tell the two masks apart when naming OV
    // parameters -- both carry the same tensor name. Null when the graph has a single mask.
    const ggml_tensor * swa_mask = nullptr;
    // The attention masks that are graph inputs, by identity: gemma-4's KV-shared layers also read them through
    // GET_ROWS, which must resolve to the same OV parameter as the attention ops
    std::set<const ggml_tensor *> kq_masks;

    std::vector<std::string> kv_names;
    size_t kv_buffer_ctx_id = 0;

    bool same_rope_params(const ModelParams & other) const {
        return mixed_rope_params == other.mixed_rope_params &&
               memcmp(rope_params, other.rope_params, sizeof(int32_t) * 16) == 0;
    }

    // swa_layers: the masks and KV write indices of these layers are separate graph inputs
    bool can_reuse_dynamically(const ModelParams & other) const {
        return same_rope_params(other) && n_rs_slots == other.n_rs_slots && has_rs_rollback == other.has_rs_rollback &&
               swa_layers == other.swa_layers;
    }

    bool can_reuse_statically(const ModelParams & other) const {
        return same_rope_params(other) && ctx == other.ctx && n_rs_slots == other.n_rs_slots &&
               has_rs_rollback == other.has_rs_rollback && swa_layers == other.swa_layers;
    }

    bool kv_buffer_changed(const ModelParams & other) const { return kv_buffer_ctx_id != other.kv_buffer_ctx_id; }
};

struct ComputeParams {
    int n_seq_active = 1;
    int seq_active_start = 0;
    int attention_size = -1;
    int attention_size_swa = -1;
    int attention_size_static = -1;  // encoder/cross-attn KV fill level (whisper)
    // OV names of the KQ mask inputs that n_seq_active (mask->ne[3]) and attention_size(_swa) (mask->ne[0]) were read from
    std::string mask_name;
    std::string mask_swa_name;
    // Sliding window width, read back from the band of ggml's own SWA mask. ggml never passes
    // n_swa down to a backend, but fill_mask() bakes it into the mask contents, so the widest
    // unmasked row recovers it. Shorter than n_swa while the sequence is still short, which is
    // harmless: every causal pair is inside the window then anyway.
    int swa_window = -1;
    int input_len = -1;
    int token_len_per_seq = -1;
    int past_kv_len = -1;
    int output_len = 1;

    int cache_rs_reset_idx = -1;
    int cache_rs_reset_len = -1;
    // SSM/DeltaNet models otionally clear cache_r and cache_s of certain slots in the cgraph
    // 3: [ 18432,     4,     1,     1] RESHAPE              cache_r_l0 (reshaped)
    //    [ 18432,     4,     1,     1]            0: NONE        cache_r_l0
    // 4: [ 18432,     1,     1,     1] VIEW                 cache_r_l0 (reshaped) (view)
    //    [ 18432,     4,     1,     1]            0: RESHAPE     cache_r_l0 (reshaped)
    // 5: [ 18432,     1,     1,     1] SCALE                cache_r_l0 (reshaped) (view) (view)
    //    [ 18432,     1,     1,     1]            0: VIEW        cache_r_l0 (reshaped) (view)

    int s_copy_active_slot_len = -1;
    // SSM/DeltaNet models otionally reorder slots of state cache, to make the active slots contiguous
    // leaf_5 is the inp->s_copy in llama-graph.cpp, eg if there are 8 slots in total and slot 3 and 7
    // are active in the current batch, leaf_5 will be [3, 7, 5, 6, 4]
    //  6: [     2,     1,     1,     1] VIEW                  (view)
    //      [     2,     1,     1,     1]            0: NONE        leaf_5
    //  7: [ 18432,     2,     1,     1] GET_ROWS             conv_states-0
    //      [ 18432,     4,     1,     1]            0: RESHAPE     cache_r_l0 (reshaped)
    //      [     2,     1,     1,     1]            1: VIEW         (view)
    //  8: [     0,     1,     1,     1] VIEW                  (view)
    //      [     2,     1,     1,     1]            0: NONE        leaf_5
    //  9: [ 18432,     0,     1,     1] GET_ROWS             node_9
    //      [ 18432,     4,     1,     1]            0: RESHAPE     cache_r_l0 (reshaped)
    //      [     0,     1,     1,     1]            1: VIEW         (view)
    // 10: [ 18432,     0,     1,     1] VIEW                 cache_r_l0 (view)
    //      [ 18432,     4,     1,     1]            0: NONE        cache_r_l0
    // 11: [ 18432,     0,     1,     1] CPY                  cache_r_l0 (view) (copy of )
    //      [ 18432,     0,     1,     1]            0: GET_ROWS    node_9
    //      [ 18432,     0,     1,     1]            1: VIEW        cache_r_l0 (view)

    // Runtime writeback offsets are refreshed per batch. Convolution SET_ROWS also supplies overlapping window counts and snapshot plane strides.
    struct RsWriteback {
        int64_t slot_begin = 0;  // first cache slot written
        int64_t src_begin = -1;  // first source column of a conv-state window
        int64_t seq_count = -1;
        int64_t snapshot_stride = -1;
        int64_t window_count = -1;
    };

    std::map<std::string, RsWriteback> rs_writebacks;
    std::map<std::string, int64_t> sampling_rows;
    std::map<std::string, int64_t> gdn_attention_rows;
    std::map<std::string, std::vector<int64_t>> recurrent_controls;
};

// defined below; declared here because GgmlOvDecoder uses it inline
std::optional<int> extract_layer_from_name(const std::string & name);

// detects the MoE expert-plane-sum ADD chain (see definition); used by supports_op too
bool is_moe_expert_sum_add(const ggml_tensor * node);

class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder {
public:
    static std::string get_tensor_name(const ggml_cgraph * cgraph, const ggml_tensor * tensor);
    struct NodeInfo {
        ggml_tensor * node;
        std::string node_name;
        std::string node_op_type;
        std::map<std::string, ggml_tensor *> node_inputs;
        std::map<std::string, std::vector<std::pair<std::string, ggml_tensor *>>> node_inputs_views;
        std::vector<std::string> node_inputs_names;
        int node_op_case = 0;
        void * data_addr;
    };

    const ggml_cgraph * get_cgraph() const { return m_cgraph; }

    // Graph decoder
    GgmlOvDecoder(ggml_cgraph * cgraph,
                  ModelParams & model_params,
                  ComputeParams & compute_params,
                  std::map<std::string, std::shared_ptr<ov::Node>> & model_weights,
                  bool is_static,
                  bool is_stateful = false,
                  bool model_is_splitted = false,
                  bool is_prefill = false,
                  int prefill_chunk_size = 256);

    // Naive graph decoder
    GgmlOvDecoder(ggml_cgraph * cgraph, std::map<std::string, std::shared_ptr<ov::Node>> & model_weights);

    virtual ov::Any get_attribute(const std::string & name) const override {
        return nullptr;
        GGML_UNUSED(name);
    }

    virtual ov::PartialShape get_input_shape(int node_idx, const std::string & name) const override;

    virtual std::vector<size_t> get_input_stride(int node_idx, const std::string & name) const override;

    virtual size_t get_view_input_size(int node_idx, const std::string & name) const override;

    virtual size_t get_view_input_offset(int node_idx, const std::string & name, size_t view_index) const override;

    virtual size_t get_view_input_src_offset(int node_idx, const std::string & name, size_t view_index) const override;

    virtual std::vector<size_t> get_view_input_stride(int node_idx,
                                                      const std::string & name,
                                                      size_t view_index) const override;

    virtual std::vector<size_t> get_view_input_src_stride(int node_idx,
                                                          const std::string & name,
                                                          size_t view_index) const override;

    virtual ov::Shape get_view_input_ggml_shape(int node_idx,
                                                const std::string & name,
                                                size_t view_index) const override;

    virtual ov::Shape get_view_input_src_ggml_shape(int node_idx,
                                                    const std::string & name,
                                                    size_t view_index) const override;

    virtual ov::PartialShape get_view_input_ov_shape(int node_idx,
                                                     const std::string & name,
                                                     size_t view_index) const override;

    virtual ov::PartialShape get_view_input_src_ov_shape(int node_idx,
                                                         const std::string & name,
                                                         size_t view_index) const override;

    virtual std::string get_view_input_name(int node_idx, const std::string & name, size_t view_index) const override;

    virtual std::string get_view_input_src_name(int node_idx,
                                                const std::string & name,
                                                size_t view_index) const override;

    virtual ov::element::Type get_input_type(int node_idx, const std::string & name) const override;

    virtual size_t get_input_size() const override;

    virtual size_t get_input_size(int node_idx) const override;

    virtual void get_input_node(size_t input_port_idx,
                                std::string & producer_name,
                                std::string & producer_output_port_name,
                                size_t & producer_output_port_index) const override {
        GGML_UNUSED(input_port_idx);
        GGML_UNUSED(producer_name);
        GGML_UNUSED(producer_output_port_name);
        GGML_UNUSED(producer_output_port_index);
    }

    virtual std::vector<std::string> get_input_names(int node_idx) const override;

    virtual ov::PartialShape get_output_shape(int node_idx) const override;

    virtual ov::element::Type get_output_type(int node_idx) const override;

    virtual std::vector<size_t> get_output_stride(int node_idx) const override;

    virtual int32_t * get_input_op_params(int node_idx, const std::string & name) const override;

    virtual int32_t * get_output_op_params(int node_idx) const override;

    virtual size_t get_output_op_offset(int node_idx) const override;

    virtual std::vector<std::string> get_output_names(int node_idx) const override;

    virtual std::string get_inplace_op_src(int node_idx) const override;

    virtual bool is_view_like_alias_of(int node_idx, const std::string & view_src_name) const override;

    virtual const std::string & get_op_type() const override;

    virtual const std::string & get_op_type(int node_idx) const override;

    virtual const std::string & get_op_name() const override;

    virtual const std::string & get_op_name(int node_idx) const override;

    virtual int32_t get_op_dynamic_dim(int node_idx) const override;

    virtual void visit_subgraph(
        std::function<void(std::shared_ptr<GgmlDecoder>, int node_idx)> node_visitor) const override;

    ggml_tensor * get_input_ggml_tensor(const std::string & name) const {
        auto it = m_inputs.find(name);
        if (it == m_inputs.end()) {
            throw std::runtime_error("OpenVINO ggml input not found: " + name);
        }
        return it->second;
    }

    virtual int get_op_case(int node_idx) const override { return m_node_info_list[node_idx].node_op_case; }

    virtual const std::map<std::string, ov::frontend::ggml::ModelInputInfo> & get_model_inputs() const override {
        return m_model_inputs;
    }

    virtual const std::map<std::string, ov::frontend::ggml::ModelExtraInputInfo> & get_model_extra_inputs() const override {
        return m_model_extra_inputs;
    }

    virtual const std::map<std::string, std::shared_ptr<ov::Node>> & get_model_weights() const override {
        return m_model_weights;
    }

    virtual std::set<std::string> get_model_output_names() const override { return m_model_output_names; }

    const std::map<std::string, ggml_tensor *> & get_model_outputs() const { return m_model_outputs; }

    virtual int get_ctx_size() const { return m_model_params.ctx; }

    virtual int get_ctx_per_seq() const { return m_model_params.ctx_per_seq; }

    virtual int get_ctx_per_seq_swa() const { return m_model_params.ctx_per_seq_swa; }

    virtual int get_n_seq() const { return m_model_params.n_seq; }

    virtual int is_swa_layer(int layer) const override {
        return std::find(m_model_params.swa_layers.begin(), m_model_params.swa_layers.end(), layer) !=
               m_model_params.swa_layers.end();
    }

    // KV head count for one layer. Sliding and full layers can differ (gemma-4 12B), so callers
    // that reinterpret a KV buffer must use this and not the model-level n_heads_kv.
    int get_n_heads_kv_for_layer(int layer) const {
        auto it = m_model_params.n_heads_kv_per_layer.find(layer);
        return it != m_model_params.n_heads_kv_per_layer.end() ? it->second : m_model_params.n_heads_kv;
    }

    // Same, for a KV cache tensor: its layer comes from the leaf name (cache_k_l<N>).
    int get_n_heads_kv_for_tensor(const ggml_tensor * kv_tensor) const {
        if (auto layer = extract_layer_from_name(std::string(kv_tensor->name)); layer.has_value()) {
            return get_n_heads_kv_for_layer(layer.value());
        }
        return m_model_params.n_heads_kv;
    }

    int get_past_kv_len() const { return m_compute_params.past_kv_len; }

    int get_input_len() const { return m_compute_params.input_len; }

    virtual int32_t * get_rope_params() const override { return const_cast<int32_t *>(m_model_params.rope_params); }

    virtual bool has_mixed_rope_params() const override { return m_model_params.mixed_rope_params; }

    virtual int get_ssm_state_size() const override { return m_model_params.state_size; }

    virtual std::map<std::string, std::string> get_kv_param_res_names() const override;

    virtual bool is_static() const override { return m_is_static; }

    virtual bool is_stateful() const override { return m_is_stateful; }

    virtual bool is_prefill() const override { return m_is_prefill; }

    int get_static_n_tokens() const { return m_is_prefill ? m_prefill_chunk_size : 1; }

    virtual bool is_splited_model() const override { return m_model_is_splitted; }

    ov::PartialShape get_graph_input_shape(const ggml_tensor * op,
                                           const ggml_tensor * input,
                                           int dynamic_dim_index = -1) const;

    static void dump_cgraph(const ggml_cgraph * cgraph, std::string & filename);

    static std::shared_ptr<ov::Node> create_weight_node(ggml_tensor * tensor, bool naive = false);

    static std::map<std::string, std::shared_ptr<ov::Node>> create_weight_nodes(ggml_cgraph * cgraph,
                                                                                bool naive = false);

    // Collect just the set of weight-tensor names referenced by the graph, without
    // building (or requantizing) any OV weight nodes. Used by topology checks like
    // is_model_splitted that only need name membership.
    static std::set<std::string> collect_weight_names(ggml_cgraph * cgraph);

    const ggml_tensor * get_tensor_used_op(const ggml_tensor * tensor) const;

    // True if the KV cache is a model input of shape [1, ctx, n_heads_kv, head_size] instead of
    // [1, 1, ctx, n_heads_kv * head_size]. Used for stateless GPU graphs when the cache holds one sequence, one token
    // per row, and is only written by SET_ROWS and read through views that split the rows into heads. The GPU
    // plugin can then fuse the cache write and read into StatelessKV: the new rows are written in place and attention
    // reads the cache without a copy.
    bool is_kvcache_4d(const ggml_tensor * cache) const;

    // True if the KV cache is an input of this graph in the 4-D layout (see is_kvcache_4d)
    bool is_kvcache_4d_input(const ggml_tensor * cache) const { return m_kvcache_4d.count(cache) != 0; }

    // True if each row of the KV cache holds one token. With `-fa off`, llama.cpp keeps the V cache transposed
    // and writes it one element per row, so its first rows do not hold the first tokens.
    bool is_kvcache_token_rows(const ggml_tensor * cache) const;

    // Reuse the KV cache ov::Tensor while pointer, type and shape stay the same (a new USM tensor costs microseconds).
    template <typename Make>
    ov::Tensor cached_kv_tensor(const ggml_tensor * kv,
                                const ov::element::Type & type,
                                const ov::Shape & shape,
                                Make && make) const {
        auto & entry = m_kv_tensor_cache[kv];
        if (!entry.tensor || entry.data != kv->data || entry.type != type || entry.shape != shape) {
            entry = {kv->data, type, shape, make(), next_tensor_id()};
        }
        m_last_kv_tensor_id = entry.id;
        return entry.tensor;
    }

    // Id of the tensor returned by the last cached_kv_tensor() call, 0 if there was no call since the last read.
    uint64_t take_last_kv_tensor_id() const { return std::exchange(m_last_kv_tensor_id, 0); }

    // Ids are never 0 and never reused: the same id means the same ov::Tensor.
    uint64_t next_tensor_id() const { return ++m_tensor_id; }

    // What one infer request port holds between inferences (dynamic GPU path).
    struct ov_port_binding {
        ov::Tensor staging;  // USM host tensor used in place of a small host tensor
        void * staging_ptr = nullptr;
        size_t staging_bytes = 0;
        uint64_t staging_id = 0;
        uint64_t bound_id = 0;  // id of the tensor bound to the port, 0 if not known
        ov::Shape bound_shape;
        ov::element::Type bound_type;
    };

    // Port state of `request`, reset when the decoder runs with another request.
    std::vector<ov_port_binding> & port_bindings(bool input, size_t n, const void * request) const {
        if (m_bindings_request != request) {
            m_input_bindings.clear();
            m_output_bindings.clear();
            m_bindings_request = request;
        }
        auto & v = input ? m_input_bindings : m_output_bindings;
        if (v.size() < n) {
            v.resize(n);
        }
        return v;
    }

    const ggml_tensor * get_tensor_from_name(const std::string & name) const;

    std::string get_hfa_history_input_name() const;

    void clear_model_weights() { m_model_weights.clear(); }

    static std::pair<ModelParams, ComputeParams> compute_llm_params(ggml_cgraph * cgraph, bool is_static);

    const ModelParams & get_model_params() const { return m_model_params; }

    const ComputeParams & get_compute_params() const { return m_compute_params; }

    void set_model_params(const ModelParams & model_params) { m_model_params = model_params; }

    void set_compute_params(const ComputeParams & compute_params) { m_compute_params = compute_params; }

    // Per-request storage: scalar runtime controls are host-produced and shape inference
    // may read them. USM host allocations let the GPU consume them without tiny uploads.
    std::map<std::string, ov::Tensor> runtime_input_storage;
    std::map<std::string, ov::Tensor> runtime_input_tensors;
    std::map<std::string, ov::Tensor> runtime_output_scratch;

    // OpenVINO device that runs the graph, e.g. GPU.1
    std::string device;

    bool m_is_static = false;
    bool m_is_stateful = false;
    bool m_is_prefill = false;
    bool m_naive = false;
    int m_prefill_chunk_size = 0;
    bool m_model_is_splitted = false;  // label the cgraph is splited or not

    static ov::Shape get_shape(const ggml_tensor * tensor);
    static std::vector<size_t> get_stride(const ggml_tensor * tensor);
    static ov::element::Type get_ov_type(const ggml_tensor * tensor);
    static std::string compute_op_type(const ggml_tensor * node);
    void add_extra_inputs();

    void update_io(ggml_cgraph * cgraph);
    bool is_bound_to(const ggml_cgraph * cgraph) const;

    // Was this decoder built for a graph with the same OUTPUT set as `cgraph`? The cache key is
    // only (n_nodes, first/last node name), which cannot see a change in which tensors are marked
    // as outputs, and the compiled model's Results are fixed at compile time.
    bool has_same_graph_io(const ggml_cgraph * cgraph) const;

    static bool is_inp_tok(const ggml_tensor * tensor, const ggml_tensor * op) {
        return op->op == GGML_OP_GET_ROWS && tensor == op->src[1] && op->src[0]->op == GGML_OP_NONE;
    }

    static bool is_inp_pos(const ggml_tensor * tensor, const ggml_tensor * op) {
        return op->op == GGML_OP_ROPE && tensor == op->src[1];
    }

    // IMROPE and VISION pack 4 stacked position planes (t/h/w/e) into inp_pos, each of length
    // n_tokens; other modes carry a single position per token.
    static int get_inp_pos_n_planes(const ggml_tensor * op) {
        const int mode = op->op_params[2];
        return (mode == GGML_ROPE_TYPE_IMROPE || mode == GGML_ROPE_TYPE_VISION || (mode & GGML_ROPE_TYPE_MROPE)) ? 4 : 1;
    }

    static bool is_inp_emb(const ggml_tensor * tensor, const ggml_tensor * op) {
        return tensor->op == GGML_OP_GET_ROWS && op->op == GGML_OP_RMS_NORM;
    }

    // Raw float input [n_embd, n_tokens]: DFlash/DSpark/EAGLE3 features into fc, or raw embd batch / EAGLE3 g-embd into RMS_NORM
    // MUL_MAT needs a weight leaf as src[0], so inp_mean (src[0] is computed) does not match
    static bool is_inp_embd_leaf(const ggml_tensor * tensor, const ggml_tensor * op) {
        if (tensor->op != GGML_OP_NONE || !(tensor->flags & GGML_TENSOR_FLAG_INPUT) || tensor->type != GGML_TYPE_F32) {
            return false;
        }
        if (op->op == GGML_OP_MUL_MAT) {
            return op->src[1] == tensor && op->src[0] != nullptr && op->src[0]->op == GGML_OP_NONE;
        }
        return op->op == GGML_OP_RMS_NORM && op->src[0] == tensor;
    }

    // true if any node of the current graph uses tensor as a raw embd input (see is_inp_embd_leaf)
    bool has_inp_embd_leaf_use(const ggml_tensor * tensor) const;

    static bool is_activation_input(const ggml_tensor * tensor, const ggml_tensor * op) {
        if (tensor == nullptr || op == nullptr || tensor->type != GGML_TYPE_F32 || tensor->ne[2] != 1 ||
            tensor->ne[3] != 1 || (tensor->buffer != nullptr && tensor->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
            return false;
        }
        return (op->op == GGML_OP_RMS_NORM || op->op == GGML_OP_L2_NORM) && op->src[0] == tensor &&
               (tensor->op == GGML_OP_NONE || tensor->op == GGML_OP_CPY);
    }

    // A 2-D float graph input feeding a matmul as src[1]. Speculative decoding hands the draft the
    // target's hidden features this way ([n_embd, n_tokens], with no GET_ROWS lookup, so none of the
    // other seeds match it) and the token count differs between the prompt pass and the shorter
    // draft blocks, so its token dim must stay dynamic.
    static bool is_inp_embd_2d(const ggml_tensor * tensor, const ggml_tensor * op) {
        return (tensor->flags & GGML_TENSOR_FLAG_INPUT) && tensor->op == GGML_OP_NONE &&
               tensor->type == GGML_TYPE_F32 && tensor->ne[2] == 1 && tensor->ne[3] == 1 &&
               op->op == GGML_OP_MUL_MAT && tensor == op->src[1];
    }

    static bool is_inp_mask(const ggml_tensor * tensor, const ggml_tensor * op) {
        return op->op == GGML_OP_CPY || (op->op == GGML_OP_FLASH_ATTN_EXT && tensor == op->src[3]) ||
               (op->op == GGML_OP_SOFT_MAX && tensor == op->src[1]);
    }

    static bool is_inp_mean(const ggml_tensor * tensor, const ggml_tensor * op) {
        return op->op == GGML_OP_MUL_MAT && tensor == op->src[1] && tensor->op == GGML_OP_NONE &&
               (tensor->flags & GGML_TENSOR_FLAG_INPUT) && tensor->type == GGML_TYPE_F32 &&
               op->src[0] != nullptr && op->src[0]->op != GGML_OP_NONE;
    }

    // per-token embedding scale [1, n_tokens] (inp->scale_rows in llama-graph.cpp)
    static bool is_inp_scale_rows(const ggml_tensor * tensor, const ggml_tensor * op) {
        return op->op == GGML_OP_MUL && tensor == op->src[1] && strcmp(tensor->name, "inp_scale_rows") == 0;
    }

    static bool is_rope_freqs_weight(const ggml_tensor * tensor, const ggml_tensor * op) {
        return op->op == GGML_OP_ROPE && tensor == op->src[2];
    }

    static bool is_recurrent_cache(const ggml_tensor * tensor) {
        return tensor != nullptr && (strncmp(tensor->name, "cache_r_l", strlen("cache_r_l")) == 0 ||
                                     strncmp(tensor->name, "cache_s_l", strlen("cache_s_l")) == 0 ||
                                     strncmp(tensor->name, "cache_ple_r_l", strlen("cache_ple_r_l")) == 0);
    }

    static bool is_recurrent_cache_reset(const ggml_tensor * node) {
        const bool is_scale_or_fill = node->op == GGML_OP_SCALE || node->op == GGML_OP_FILL;
        return is_scale_or_fill && node->view_src != nullptr && is_recurrent_cache(node->view_src);
    }

    static bool is_gdn_snapshot_writeback(const ggml_tensor * node) {
        if (!(node != nullptr && node->op == GGML_OP_CPY && node->src[0] != nullptr &&
               node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr &&
               node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET && node->src[0]->src[0]->op_params[0] > 1 &&
               node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->view_src != nullptr &&
               node->src[1]->view_src == node->view_src && node->src[0]->ne[0] == node->src[1]->ne[0] &&
               node->src[1]->nb[1] > 0 && node->src[1]->nb[1] == ggml_row_size(node->type, node->ne[0]) &&
               node->src[1]->nb[2] % node->src[1]->nb[1] == 0 &&
               node->src[1]->view_offs % node->src[1]->nb[1] == 0)) {
            return false;
        }
        const auto * source = node->src[0];
        const auto * destination = node->src[1];
        const auto * packed = source->src[0];
        if (node->type != GGML_TYPE_F32 || source->type != node->type || destination->type != node->type ||
            node->view_src->type != node->type || !ggml_is_contiguous(node->view_src) ||
            packed->nb[1] == 0 || source->view_offs % packed->nb[1] != 0 ||
            source->nb[0] != sizeof(float) || destination->nb[0] != sizeof(float) ||
            source->ne[3] != 1 || destination->ne[3] != 1) {
            return false;
        }
        for (int i = 0; i < GGML_MAX_DIMS; ++i) {
            if (source->ne[i] <= 0 || source->ne[i] != destination->ne[i]) {
                return false;
            }
        }
        const size_t plane_stride = destination->nb[2] / destination->nb[1];
        if (plane_stride == 0 || size_t(destination->ne[1]) > plane_stride -
            (destination->view_offs / destination->nb[1]) % plane_stride) {
            return false;
        }
        for (const auto * view : {source, destination}) {
            size_t remaining = ggml_nbytes(view == source ? packed : node->view_src);
            if (view->view_offs > remaining || remaining - view->view_offs < sizeof(float)) {
                return false;
            }
            remaining -= view->view_offs + sizeof(float);
            for (int i = 0; i < GGML_MAX_DIMS; ++i) {
                const size_t count = view->ne[i] - 1;
                if (view->nb[i] != 0 && count > remaining / view->nb[i]) {
                    return false;
                }
                remaining -= count * view->nb[i];
            }
        }
        return true;
    }

    static bool is_sampling_view(const ggml_tensor * node) {
        return node != nullptr && node->op == GGML_OP_VIEW && node->src[0] != nullptr &&
               node->src[0]->op == GGML_OP_PAD && node->ne[0] == node->src[0]->ne[0] &&
               node->ne[1] == 1 && node->ne[2] == 1 && node->ne[3] == 1;
    }

    static bool is_sampling_top_k(const ggml_tensor * node) {
        return node != nullptr && node->op == GGML_OP_TOP_K && node->src[0] != nullptr &&
               node->src[0]->op == GGML_OP_RESHAPE && is_sampling_view(node->src[0]->src[0]);
    }

    bool is_direct_gdn_view(const ggml_tensor * node) const;

    static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) {
        return is_recurrent_cache(tensor) || is_kvcache(tensor, op);
    }

    static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) {
        if (tensor == nullptr || is_recurrent_cache(tensor)) {
            return false;
        }
        return (tensor->buffer != nullptr && tensor->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY) ||
               (op != nullptr && op->op == GGML_OP_SET_ROWS && op->src[2] == tensor);
    }

    static bool is_conv_state_writeback(const ggml_tensor * node) {
        return node->op == GGML_OP_CPY && node->view_src != nullptr && is_recurrent_cache(node->view_src) &&
               node->src[0] != nullptr && node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr &&
               node->src[0]->src[0]->op == GGML_OP_CONCAT && node->src[1] != nullptr &&
               node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src;
    }

    // The final-state writeback of SSM_SCAN (K == 1): the state tail of the packed [y | state]
    // output copied into a slot block of the recurrent cache.
    static bool is_ssm_state_writeback(const ggml_tensor * node) {
        if (!(node != nullptr && node->op == GGML_OP_CPY && node->view_src != nullptr && node->src[0] != nullptr &&
              node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr &&
              node->src[0]->src[0]->op == GGML_OP_SSM_SCAN && node->src[0]->src[0]->op_params[0] == 1 &&
              node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW &&
              node->src[1]->view_src == node->view_src)) {
            return false;
        }
        const auto * scan = node->src[0]->src[0];
        const auto * src = node->src[0];
        const auto * dst = node->src[1];
        if (node->type != GGML_TYPE_F32 || src->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 ||
            src->ne[2] != 1 || src->ne[3] != 1) {
            return false;
        }
        for (int i = 0; i < GGML_MAX_DIMS; ++i) {
            if (src->ne[i] != dst->ne[i]) {
                return false;
            }
        }
        return dst->nb[1] > 0 && dst->view_offs % dst->nb[1] == 0 &&
               src->view_offs == (size_t) ggml_nelements(scan->src[1]) * ggml_type_size(scan->type);
    }

    // build_conv_state_store writes overlapping [history, window, channel, seq] windows into newest-first rollback planes.
    // Match this layout separately from general SET_ROWS.
    static bool is_conv_state_snapshot_writeback(const ggml_tensor * node);

    // SET_ROWS into a column range of each row of a plain 2-D buffer, e.g. build_layer_inp_dev(): every enabled layer
    // input goes to view_2d(layer_inp_dev, n_embd, n_batch, nb1, col * n_embd * elem) at the batch rows of the ubatch.
    // The buffer sits in a regular device buffer, so is_kvcache() matches it: check this first
    static bool is_column_set_rows(const ggml_tensor * node) {
        if (node == nullptr || node->op != GGML_OP_SET_ROWS || node->src[2] == nullptr ||
            node->src[2]->op != GGML_OP_VIEW) {
            return false;
        }
        const ggml_tensor * dst = node->src[2];
        const ggml_tensor * buf = dst->view_src;
        return buf != nullptr && buf->op == GGML_OP_NONE && !is_recurrent_cache(buf) && buf->ne[2] == 1 &&
               buf->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && dst->ne[0] < buf->ne[0] &&
               dst->nb[0] == buf->nb[0] && dst->nb[1] == buf->nb[1] && dst->ne[1] == buf->ne[1];
    }

    // SET_ROWS into a KV cache, directly or through the [1, n] reshape of the transposed V cache with `-fa off`.
    // Other SET_ROWS write rows of a compute tensor, e.g. the MoE expert-group mask
    static bool is_kvcache_write(const ggml_tensor * node) {
        const ggml_tensor * dst = node->src[2];
        return dst != nullptr && is_kvcache(dst->view_src != nullptr ? dst->view_src : dst, nullptr);
    }

    // GET_ROWS batched over ggml dims 2 and 3, e.g. the MoE expert-group scores
    // ggml_get_rows(ggml_reshape_4d(groups, 1, n_exp_per_group, n_groups, n_tokens), top_groups)
    static bool is_get_rows_batched_4d(const ggml_tensor * node) {
        return node->op == GGML_OP_GET_ROWS && !ggml_is_quantized(node->src[0]->type) &&
               node->src[1]->ne[1] == node->src[0]->ne[2] && node->src[1]->ne[2] == node->src[0]->ne[3] &&
               node->src[1]->ne[3] == 1;
    }

    static bool is_kv_idx(const ggml_tensor * tensor, const ggml_tensor * op) {
        return op->op == GGML_OP_SET_ROWS && op->src[1] == tensor;
    }

    bool is_swa_mask(const ggml_tensor * tensor) const {
        return m_model_params.swa_mask != nullptr && tensor == m_model_params.swa_mask;
    }

    bool is_kq_mask(const ggml_tensor * tensor) const { return m_model_params.kq_masks.count(tensor) != 0; }

    // A graph-input index list of GET_ROWS: out_ids, or the inp->s_copy leaf when build_rs gathers
    // every recurrent state at once.
    static bool is_get_rows_input_idx(const ggml_tensor * tensor, const ggml_tensor * op) {
        return op->op == GGML_OP_GET_ROWS && tensor == op->src[1] && op->src[0]->op != GGML_OP_NONE &&
               op->src[1]->op == GGML_OP_NONE;
    }

    // out_ids, which selects the output rows. The recurrent state gather reads a state cache instead.
    static bool is_output_idx(const ggml_tensor * tensor, const ggml_tensor * op) {
        if (!is_get_rows_input_idx(tensor, op)) {
            return false;
        }
        const ggml_tensor * data = op->src[0];
        while (data != nullptr && (data->op == GGML_OP_VIEW || data->op == GGML_OP_RESHAPE)) {
            data = data->src[0];
        }
        return !is_recurrent_cache(data);
    }

    // the state permutation index input used in SSM/DeltaNet models (inp->s_copy in llama-graph.cpp)
    static bool is_inp_s_copy(const ggml_tensor * tensor, const ggml_tensor * op) {
        return op->op == GGML_OP_GET_ROWS && tensor == op->src[1] &&
               op->src[0]->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY;
    }

    std::string get_graph_input_ov_name(const ggml_tensor * tensor, const ggml_tensor * op) const {
        if (is_inp_pos(tensor, op)) {
            return "inp_pos";
        }
        if (is_inp_emb(tensor, op)) {
            return "embd";
        }
        if (is_inp_mask(tensor, op)) {
            // Give the two attention masks distinct OV parameter names.
            //
            // An interleaved-SWA model builds one full-attention mask and one sliding-window mask,
            // but build_attn_inp_kq_mask() names them identically, so keying a parameter off
            // tensor->name alone makes the second mask OVERWRITE the first in m_model_inputs: both
            // attention types then read a single parameter, and the windowed layers silently run
            // against an unbanded mask. Disambiguate using the SWA layer set computed in
            // compute_llm_params(), which classifies by mask tensor identity rather than by name.
            //
            // When no SWA layer was found there is only one mask in play, so the plain name is
            // correct and no _swa parameter is created.
            if (m_model_params.swa_layers.empty()) {
                return "self_kq_mask";
            }
            return is_swa_mask(tensor) ? "self_kq_mask_swa" : "self_kq_mask";
        }
        return tensor->name;
    }

private:
    void set_input_output();
    int compute_op_case(const ggml_tensor * node) const;
    bool is_gdn_out_prescaled(const ggml_tensor * gdn) const;
    bool node_is_used_as_src(const int node_idx);
    void compute_model_inputs();
    void compute_model_outputs();

    // True if tensor is the inp->s_copy index leaf gathered by a recurrent state cache GET_ROWS
    // (possibly through a VIEW), so it gets a dynamic [1,1,1,-1] graph-input shape.
    bool is_s_copy_leaf(const ggml_tensor * tensor) const;

    // Infer and propagate dynamic-dimension indices for all tensors in the GGML graph.
    void compute_node_dynamic_dims();

    void validate_cgraph() const;

    ggml_cgraph * m_cgraph = nullptr;
    std::map<std::string, ggml_tensor *> m_inputs;

    std::map<std::string, ov::frontend::ggml::ModelInputInfo> m_model_inputs;
    std::map<std::string, ov::frontend::ggml::ModelExtraInputInfo> m_model_extra_inputs;
    std::map<std::string, std::shared_ptr<ov::Node>> m_model_weights;
    std::map<std::string, ggml_tensor *> m_model_outputs;
    std::set<std::string> m_model_output_names;
    // The output set the compiled model was built from, for has_same_graph_io().
    std::set<std::string> m_built_output_names;
    std::vector<NodeInfo> m_node_info_list;
    std::map<ggml_tensor *, int> m_node_dynamic_dims;
    std::set<const ggml_tensor *> m_kvcache_4d;

    struct kv_tensor_entry {
        const void * data = nullptr;
        ov::element::Type type;
        ov::Shape shape;
        ov::Tensor tensor;
        uint64_t id = 0;
    };

    mutable std::map<const ggml_tensor *, kv_tensor_entry> m_kv_tensor_cache;
    mutable uint64_t m_tensor_id = 0;
    mutable uint64_t m_last_kv_tensor_id = 0;
    mutable std::vector<ov_port_binding> m_input_bindings;
    mutable std::vector<ov_port_binding> m_output_bindings;
    mutable const void * m_bindings_request = nullptr;

    ModelParams m_model_params;
    ComputeParams m_compute_params;
};

void print_tensor_address_map(const ggml_cgraph * cgraph);