transcribe-cpp-sys 0.5.1

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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
#include "utils.h"

#include "ggml-impl.h"
#include "ggml-openvino/ggml-openvino-extra.h"

#include <cmath>
#include <cstddef>
#include <ctime>
#include <memory>
#include <openvino/op/add.hpp>
#include <openvino/op/clamp.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/concat.hpp>
#include <openvino/op/convert.hpp>
#include <openvino/op/cos.hpp>
#include <openvino/op/divide.hpp>
#include <openvino/op/gather.hpp>
#include <openvino/op/greater_eq.hpp>
#include <openvino/op/less.hpp>
#include <openvino/op/logical_or.hpp>
#include <openvino/op/maximum.hpp>
#include <openvino/op/multiply.hpp>
#include <openvino/op/range.hpp>
#include <openvino/op/reshape.hpp>
#include <openvino/op/select.hpp>
#include <openvino/op/shape_of.hpp>
#include <openvino/op/sin.hpp>
#include <openvino/op/slice.hpp>
#include <openvino/op/split.hpp>
#include <openvino/op/squeeze.hpp>
#include <openvino/op/subtract.hpp>
#include <openvino/op/transpose.hpp>
#include <openvino/op/unsqueeze.hpp>
#include <openvino/op/util/precision_sensitive_attribute.hpp>
#include <string>

namespace ov {
namespace frontend {
namespace ggml {

void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max_inputs) {
    auto input_size = context.get_input_size();
    FRONT_END_OP_CONVERSION_CHECK(input_size >= min_inputs, "Got less inputs than expected");
    FRONT_END_OP_CONVERSION_CHECK(input_size <= max_inputs, "Got more inputs than expected");
}

std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf> & shape,
                                         const std::vector<int> & dims) {
    using namespace ov::op;
    const auto zero = v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
    const auto dims_const = v0::Constant::create(ov::element::i32, ov::Shape{dims.size()}, dims);
    return std::make_shared<v8::Gather>(shape, dims_const, zero);
}

std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node> & node, const std::vector<int> & dims) {
    return get_dimensions(std::make_shared<ov::op::v3::ShapeOf>(node), dims);
}

OutputVector rename_outputs_with_suffix(const OutputVector & outputs, const std::string & suffix) {
    for (const auto & output : outputs) {
        auto node = output.get_node_shared_ptr();
        std::string name = node->get_friendly_name();
        name += "_";
        name += suffix;
        node->set_friendly_name(name);
        // Uncomment to dump every node's inferred shape (used to hunt down dynamic dims on NPU).
        // std::cout << name << "  " << output.get_partial_shape() << std::endl;
    }
    return outputs;
}

namespace {
ov::Output<ov::Node> rope_yarn_ramp_mix(int num_elements, const float corr_dims[2], float ext_factor) {
    std::vector<float> dim_ids_vec(num_elements);
    std::iota(dim_ids_vec.begin(), dim_ids_vec.end(), 0.0f);
    auto dim_ids = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, (size_t) num_elements}, dim_ids_vec);
    auto corr_low = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {corr_dims[0]});
    auto corr_high = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {corr_dims[1]});
    auto denom = std::make_shared<ov::op::v1::Maximum>(
        std::make_shared<ov::op::v1::Subtract>(corr_high, corr_low),
        ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {0.001f}));
    auto ramp_y =
        std::make_shared<ov::op::v1::Divide>(std::make_shared<ov::op::v1::Subtract>(dim_ids, corr_low), denom);
    auto ramp_clamped = std::make_shared<ov::op::v0::Clamp>(ramp_y, 0.0f, 1.0f);
    // rope_yarn_ramp returns (1 - clamp(y)), so invert before scaling
    auto one = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {1.0f});
    auto ramp_inverted = std::make_shared<ov::op::v1::Subtract>(one, ramp_clamped);
    auto ext_factor_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {ext_factor});
    auto ramp_mix = std::make_shared<ov::op::v1::Multiply>(ramp_inverted, ext_factor_node);
    return ramp_mix;
}

}  // namespace

std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(int32_t * rope_params,
                                                           std::shared_ptr<ov::Node> inp_pos,
                                                           std::shared_ptr<ov::Node> rope_freqs_weight,
                                                           int mode,
                                                           bool stateful,
                                                           int64_t head_dim) {
    constexpr int TYPE_IMROPE = 2;
    constexpr int TYPE_VISION = 3;
    constexpr int TYPE_MROPE = 4;

    const bool is_imrope = (mode == TYPE_IMROPE);
    const bool is_vision = (mode == TYPE_VISION);
    const bool is_mrope = (mode == TYPE_MROPE);
    const bool is_multi = is_imrope || is_vision || is_mrope;

    if (stateful) {
        inp_pos =
            std::make_shared<ov::op::v0::Squeeze>(inp_pos, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
        inp_pos = std::make_shared<ov::op::v0::Convert>(inp_pos, ov::element::f32);
        auto pos_perm =
            std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{2, 1, 0});
        inp_pos = std::make_shared<ov::op::v1::Transpose>(inp_pos, pos_perm);
    } else if (is_multi) {
        inp_pos = std::make_shared<ov::op::v0::Convert>(inp_pos, ov::element::f32);
        auto pos_shape = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{5}, {0, 0, 0, 4, -1});
        inp_pos = std::make_shared<ov::op::v1::Reshape>(inp_pos, pos_shape, true);
        auto pos_transpose_shape =
            std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{5}, std::vector<int64_t>{0, 1, 2, 4, 3});
        inp_pos = std::make_shared<ov::op::v1::Transpose>(inp_pos, pos_transpose_shape);
    } else {
        inp_pos = std::make_shared<ov::op::v0::Convert>(inp_pos, ov::element::f32);
        auto pos_perm =
            std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 3, 1, 2});
        inp_pos = std::make_shared<ov::op::v1::Transpose>(inp_pos, pos_perm);
    }

    float freq_base;
    float freq_scale;
    float ext_factor;
    float attn_factor;
    float beta_fast;
    float beta_slow;
    const int n_dims = rope_params[1];
    const size_t n_dims_half = n_dims >> 1;
    const bool truncate = rope_params[3] == 0;
    const int n_ctx_orig = rope_params[4];
    memcpy(&freq_base, rope_params + 5, sizeof(float));
    memcpy(&freq_scale, rope_params + 6, sizeof(float));
    memcpy(&ext_factor, rope_params + 7, sizeof(float));
    memcpy(&attn_factor, rope_params + 8, sizeof(float));
    memcpy(&beta_fast, rope_params + 9, sizeof(float));
    memcpy(&beta_slow, rope_params + 10, sizeof(float));

    const float theta_scale = powf(freq_base, -2.0f / n_dims);

    Output<Node> theta;
    float mscale = attn_factor;
    if (is_multi) {
        const size_t num_pairs = is_vision ? (n_dims > 0 ? (size_t) n_dims : (size_t) (head_dim / 2)) : n_dims_half;
        int sections[4];
        memcpy(sections, rope_params + 11, sizeof(int) * 4);
        int sect_dims = sections[0] + sections[1] + sections[2] + sections[3];
        if (sect_dims <= 0) {
            sect_dims = num_pairs;
        }
        int sec_w = sections[0] + sections[1];
        int sec_e = sec_w + sections[2];
        std::vector<int64_t> gather_indices(num_pairs);
        std::vector<float> factor(num_pairs);
        for (size_t j = 0; j < num_pairs; j++) {
            int sector = j % sect_dims;
            int plane = 0;
            if (is_imrope) {
                if (sector % 3 == 1 && sector < 3 * sections[1]) {
                    plane = 1;
                } else if (sector % 3 == 2 && sector < 3 * sections[2]) {
                    plane = 2;
                } else if (sector % 3 == 0 && sector < 3 * sections[0]) {
                    plane = 0;
                } else {
                    plane = 3;
                }
                factor[j] = std::pow(theta_scale, j);
            } else if (is_vision) {
                int p_idx = 0;
                if (sector < sections[0]) {
                    plane = 0;
                    p_idx = sector;
                } else if (sector < sections[0] + sections[1]) {
                    plane = 1;
                    p_idx = sector - sections[0];
                } else if (sector < sec_w + sections[2]) {
                    plane = 2;
                    p_idx = sector - sec_w;
                } else {
                    plane = 3;
                    p_idx = sector - sec_e;
                }
                factor[j] = std::pow(theta_scale, p_idx);
            } else {
                if (sector >= sections[0] && sector < sec_w) {
                    plane = 1;
                } else if (sector >= sec_w && sector < sec_e) {
                    plane = 2;
                } else if (sector >= sec_e) {
                    plane = 3;
                } else {
                    plane = 0;
                }
                factor[j] = std::pow(theta_scale, j);
            }
            gather_indices[j] = plane;
        }
        auto gather_indices_const =
            std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{num_pairs}, gather_indices);
        auto gather_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {4});
        inp_pos = std::make_shared<ov::op::v8::Gather>(inp_pos, gather_indices_const, gather_axis);
        Output<Node> factor_node =
            std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{num_pairs}, factor);
        if (rope_freqs_weight) {
            Output<Node> rope_factors = std::make_shared<ov::op::v8::Slice>(
                rope_freqs_weight,
                ov::op::v0::Constant::create(ov::element::i64, {1}, {0}),
                ov::op::v0::Constant::create(ov::element::i64, {1}, {(int64_t) num_pairs}),
                ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
                ov::op::v0::Constant::create(ov::element::i64, {1}, {rope_freqs_weight->get_output_partial_shape(0).rank().get_length() - 1}));
            rope_factors = std::make_shared<ov::op::v1::Reshape>(
                rope_factors,
                ov::op::v0::Constant::create(ov::element::i64, {1}, {(int64_t) num_pairs}),
                false);
            factor_node = std::make_shared<ov::op::v1::Divide>(factor_node, rope_factors);
        }
        auto theta_extrap = std::make_shared<ov::op::v1::Multiply>(inp_pos, factor_node);
        auto theta_interp = std::make_shared<ov::op::v1::Multiply>(
            theta_extrap, ov::op::v0::Constant::create(ov::element::f32, {1}, {freq_scale}));
        if (ext_factor == 0.0f) {
            theta = theta_interp;
        } else {
            float corr_dims[2];
            ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, truncate, corr_dims);
            auto ramp_mix = rope_yarn_ramp_mix(num_pairs, corr_dims, ext_factor);
            Output<Node> one = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {1.0f});
            auto one_minus_ramp = std::make_shared<ov::op::v1::Subtract>(one, ramp_mix);
            theta = std::make_shared<ov::op::v1::Add>(
                std::make_shared<ov::op::v1::Multiply>(theta_interp, one_minus_ramp),
                std::make_shared<ov::op::v1::Multiply>(theta_extrap, ramp_mix));
            mscale *= (1.0f + 0.1f * std::log(1.0f / freq_scale));
        }
    } else {
        std::vector<float> factor(n_dims_half);
        Output<Node> freq_factors;
        float corr_dims[2];
        ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, truncate, corr_dims);
        factor[0] = 1.0f;
        for (size_t i = 1; i < factor.size(); i++) {
            factor[i] = theta_scale * factor[i - 1];
        }
        if (stateful) {
            freq_factors =
                std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1, 1, factor.size()}, factor);
        } else {
            freq_factors =
                std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1, 1, 1, factor.size()}, factor);
        }
        if (rope_freqs_weight) {
            Output<Node> rope_factors = std::make_shared<ov::op::v8::Slice>(
                rope_freqs_weight,
                ov::op::v0::Constant::create(ov::element::i64, {1}, {0}),
                ov::op::v0::Constant::create(ov::element::i64, {1}, {(int64_t) n_dims_half}),
                ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
                ov::op::v0::Constant::create(ov::element::i64, {1}, {rope_freqs_weight->get_output_partial_shape(0).rank().get_length() - 1}));
            if (stateful) {
                rope_factors = std::make_shared<ov::op::v1::Reshape>(
                    rope_factors,
                    ov::op::v0::Constant::create(ov::element::i64, {3}, {(int64_t) 1, (int64_t) 1, (int64_t) n_dims_half}),
                    false);
            } else {
                rope_factors = std::make_shared<ov::op::v1::Reshape>(
                    rope_factors,
                    ov::op::v0::Constant::create(ov::element::i64, {4}, {(int64_t) 1, (int64_t) 1, (int64_t) 1, (int64_t) n_dims_half}),
                    false);
            }
            freq_factors = std::make_shared<ov::op::v1::Divide>(freq_factors, rope_factors);
        }

        auto theta_extrap = std::make_shared<ov::op::v1::Multiply>(freq_factors, inp_pos);
        auto theta_interp = std::make_shared<ov::op::v1::Multiply>(
            theta_extrap, ov::op::v0::Constant::create(ov::element::f32, {1}, {freq_scale}));

        if (ext_factor == 0.0f) {
            theta = theta_interp;
        } else {
            auto ramp_mix = rope_yarn_ramp_mix(n_dims_half, corr_dims, ext_factor);
            Output<Node> one;
            if (stateful) {
                one = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1}, {1.0f});
            } else {
                one = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {1.0f});
            }
            auto one_minus_ramp = std::make_shared<ov::op::v1::Subtract>(one, ramp_mix);

            theta =
                std::make_shared<ov::op::v1::Add>(std::make_shared<ov::op::v1::Multiply>(theta_interp, one_minus_ramp),
                                                  std::make_shared<ov::op::v1::Multiply>(theta_extrap, ramp_mix));
            mscale *= (1.0f + 0.1f * std::log(1.0f / freq_scale));
        }
    }

    // Keep the ROPE ANGLE in f32 even under INFERENCE_PRECISION_HINT=f16.
    //
    // Everything above builds theta = pos * freq_factors with a declared f32 type, but a declared
    // element type is not an execution precision: under the f16 hint the GPU plugin compresses these
    // subgraphs to f16 anyway. theta's magnitude IS the token position, so at position 6525 it lands
    // where f16 spacing is 4 and the value is not even representable. Worse, a model whose freq_base
    // and head_dim make factor[0] == 1.0 exactly feeds the raw position in as the top-frequency
    // angle, so an absolute error of 1-2 becomes an error of 1-2 RADIANS -- up to a third of a cycle. Sin/Cos of an angle wrong by radians is not approximately
    // right, it is arbitrary, and trig amplifies the error without bound.
    //
    // Measured on a large decoder-only model at inp_pos=6525, same device, f16 vs f32 execution: the
    // whole Q/K projection chain is clean at rel ~1e-4, then Cos jumps to rel 0.124 and Sin to 0.155,
    // and K right after the rotation carries rel 0.081. The error is depth-dependent because f16
    // spacing grows with magnitude: sin rel is 0.006 at position 512 and 0.16 at 6525.
    //
    // mark_as_precision_sensitive disables fp16 compression of the subgraph feeding an input, which is
    // exactly the guarantee needed. Marking Sin/Cos's input covers the whole theta chain back to the
    // Convert of inp_pos. The cost is negligible: theta is a few dozen values per token, against the
    // matmuls that dominate. The rotation itself and everything downstream stay f16.
    //
    // Off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. It changes the RoPE of every model,
    // it is validated on one model on the GPU only, and on an f32 path the round trip below makes
    // cos and sin less accurate.
    const bool pin_angle = ggml_openvino_getenv_int("GGML_OPENVINO_ROPE_F32_ANGLE") != 0;

    auto cos_op = std::make_shared<ov::op::v0::Cos>(theta);
    auto sin_op = std::make_shared<ov::op::v0::Sin>(theta);
    if (pin_angle) {
        ov::mark_as_precision_sensitive(cos_op->input(0));
        ov::mark_as_precision_sensitive(sin_op->input(0));
    }
    Output<Node> cos_theta = cos_op;
    Output<Node> sin_theta = sin_op;

    if (mscale != 1.0f) {
        auto mscale_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {mscale});

        auto cos_scaled = std::make_shared<ov::op::v1::Multiply>(cos_theta, mscale_node);
        auto sin_scaled = std::make_shared<ov::op::v1::Multiply>(sin_theta, mscale_node);
        // Mark this Constant's input too. Marking only Sin/Cos keeps those nodes f32 but leaves the
        // sibling mscale Constant to be compressed to f16, and the pass does not reconcile the pair,
        // so compilation fails with "Arguments do not have the same element type".
        if (pin_angle) {
            ov::mark_as_precision_sensitive(cos_scaled->input(1));
            ov::mark_as_precision_sensitive(sin_scaled->input(1));
        }
        cos_theta = cos_scaled;
        sin_theta = sin_scaled;
    }

    // Close the f32 island explicitly with an f16 round trip.
    //
    // ConvertPrecision does not insert the boundary Convert: with only the marking above, the f32
    // region propagates forward through the shape-only ops of the cos/sin expansion and then collides
    // with f16 data in the rotation, so the type mismatch just moves one step down the graph.
    //
    // Rounding the RESULT of the trig is harmless -- cos/sin are in [-1,1], where f16 spacing is ~6e-4,
    // the ordinary f16 cost accepted everywhere else. What must not be rounded is the ANGLE, which the
    // marking above protects. So this spends the cheap rounding to buy a type-consistent graph: the
    // chain from inp_pos through Sin/Cos stays f32, everything downstream is f16, and the transition is
    // a node we control rather than one the pass has to infer.
    //
    // Declared types are f32 on both sides at build time, so the frontend sees no type change. On an
    // f32 path (the CPU device in test-backend-ops) the two Converts still round cos and sin to f16.
    if (pin_angle) {
        auto pin_boundary = [](Output<Node> x) -> Output<Node> {
            auto down = std::make_shared<ov::op::v0::Convert>(x, ov::element::f16);
            return std::make_shared<ov::op::v0::Convert>(down, ov::element::f32);
        };
        cos_theta = pin_boundary(cos_theta);
        sin_theta = pin_boundary(sin_theta);
    }

    return std::make_pair(sin_theta, cos_theta);
}

ov::Output<ov::Node> process_view_input(const NodeContext & context, int input_index, int slice_len, int axis) {
    // Only works for VIEW operations that does a non-strided slice with optinal reshape on the slice result.
    // The function only does the slice part, the reshape (if any) should be handled by the caller.
    // Default axis is -1, which means slicing the last dimension.
    // If the VIEW reshapes the result, `slice_len` should be provided
    auto input = context.get_input(input_index);
    auto * op_params = (size_t *) context.get_input_op_params(input_index);
    auto src_stride = context.get_input_stride(input_index);

    int64_t slice_start = op_params[0] / src_stride[3];
    if (slice_len == 0) {
        slice_len = context.get_input_shape(input_index)[3].get_length();
    }
    int64_t slice_end = slice_start + slice_len;

    auto begin = ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_start});
    auto end = ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_end});
    auto stride = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
    ov::Output<ov::Node> axes;
    if (axis == -1) {
        axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {context.is_stateful() ? 2 : 3});
    } else {
        axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {axis});
    }
    auto sliced = std::make_shared<ov::op::v8::Slice>(input, begin, end, stride, axes);
    return sliced;
}

namespace {

// Walk a dequantization chain, gathering `indices` out of every leaf Constant that is indexed by
// the gathered axis, and rebuild the chain on top of the gathered rows. Only the node types
// make_intX_weights emits are recognized; anything else aborts the rewrite (nullptr).
std::shared_ptr<ov::Node> rebuild_on_gathered_rows(const ov::Output<ov::Node> & out,
                                                   const ov::Output<ov::Node> & indices,
                                                   int64_t rows,
                                                   size_t idx_rank,
                                                   bool & saw_compressed,
                                                   size_t depth) {
    static constexpr size_t max_depth = 8;
    if (depth > max_depth) {
        return nullptr;
    }
    auto node = out.get_node_shared_ptr();

    if (auto cnst = ov::as_type_ptr<ov::op::v0::Constant>(node)) {
        const auto & shape = cnst->get_shape();
        const auto type = cnst->get_element_type();
        if (type == ov::element::u4 || type == ov::element::i4 || type == ov::element::u8 ||
            type == ov::element::i8) {
            saw_compressed = true;
        }
        if (shape.empty() || static_cast<int64_t>(shape[0]) != rows) {
            // Scalar or already-broadcast operand (e.g. a single zero point): share it unchanged.
            return cnst;
        }
        auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
        return std::make_shared<ov::op::v8::Gather>(cnst, indices, axis);
    }

    if (auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(node)) {
        // The only Reshape in the chain collapses the group axis back into the row, [N,K/G,G] ->
        // [N,K]. On gathered rows the leading N becomes the index dims, so keep those and collapse
        // whatever remains.
        const auto & ps = reshape->get_output_partial_shape(0);
        if (ps.rank().is_dynamic() || ps.rank().get_length() != 2) {
            return nullptr;
        }
        auto input = rebuild_on_gathered_rows(reshape->input_value(0), indices, rows, idx_rank,
                                              saw_compressed, depth + 1);
        if (!input) {
            return nullptr;
        }
        std::vector<int64_t> target(idx_rank, 0);
        target.push_back(-1);
        auto target_shape = ov::op::v0::Constant::create(ov::element::i64, {target.size()}, target);
        return std::make_shared<ov::op::v1::Reshape>(input, target_shape, true);
    }

    if (ov::is_type<ov::op::v0::Convert>(node) || ov::is_type<ov::op::v1::Multiply>(node) ||
        ov::is_type<ov::op::v1::Subtract>(node)) {
        ov::OutputVector args;
        args.reserve(node->get_input_size());
        for (size_t i = 0; i < node->get_input_size(); i++) {
            auto arg = rebuild_on_gathered_rows(node->input_value(i), indices, rows, idx_rank,
                                                saw_compressed, depth + 1);
            if (!arg) {
                return nullptr;
            }
            args.push_back(arg);
        }
        return node->clone_with_new_inputs(args);
    }

    return nullptr;
}

}  // namespace

std::shared_ptr<ov::Node> gather_compressed_rows(const ov::Output<ov::Node> & weights,
                                                 const ov::Output<ov::Node> & indices) {
    // Below this the dequantized table is small enough that the extra nodes are not worth it.
    static constexpr int64_t min_elements = 1 << 20;

    const auto & ps = weights.get_partial_shape();
    const auto & idx_ps = indices.get_partial_shape();
    if (ps.rank().is_dynamic() || ps.rank().get_length() != 2 || ps[0].is_dynamic() ||
        ps[1].is_dynamic() || idx_ps.rank().is_dynamic()) {
        return nullptr;
    }
    if (ps[0].get_length() * ps[1].get_length() < min_elements) {
        return nullptr;
    }

    bool saw_compressed = false;
    auto gathered = rebuild_on_gathered_rows(weights, indices, ps[0].get_length(),
                                             idx_ps.rank().get_length(), saw_compressed, 0);
    return saw_compressed ? gathered : nullptr;
}

ov::Output<ov::Node> get_kq_mask_input(const NodeContext & context, size_t input_index) {
    const auto & name = context.get_input_names()[input_index];
    const std::string sliced = name == "self_kq_mask_swa"                  ? "KQ_mask_swa_sliced" :
                               name == "self_kq_mask" || name == "KQ_mask" ? "KQ_mask_sliced" :
                                                                             std::string();
    if (!sliced.empty() && context.has_input(sliced)) {
        return context.get_input(sliced);
    }
    return context.get_input(input_index);
}

ov::Output<ov::Node> process_view_input_new(const NodeContext & context, int input_index) {
    auto input = context.get_input(input_index);

    // Check if this input has view inputs
    size_t view_input_size = context.get_view_input_size(input_index);
    if (view_input_size == 0) {
        // No view inputs, return the input as is
        return input;
    }

    // A VIEW over the packed SSM_SCAN output selects one whole Concat part: y at offset 0, the
    // final state after it. The y length is token-dependent, so a static Slice of the flat
    // tensor would bake in the captured token count; return the native part instead.
    if (view_input_size == 1 && input.get_node_shared_ptr()->get_rt_info().count(GGML_OV_SSM_SCAN_PACKED)) {
        const bool is_y = context.get_view_input_offset(input_index, 0) == 0;
        auto part = input.get_node_shared_ptr()->input_value(is_y ? 0 : 1).get_node_shared_ptr()->input_value(0);
        if (is_y) {
            // y keeps its native [n_seqs, n_tokens, n_head, head_dim] layout
            return part;
        }
        // state [n_seqs, n_head, head_dim, d_state] -> view layout [1, 1, n_seqs, d_state * d_inner]
        auto n_seqs = get_dimensions(std::make_shared<ov::op::v3::ShapeOf>(part, ov::element::i64), {0});
        auto target = std::make_shared<ov::op::v0::Concat>(
            ov::OutputVector{ov::op::v0::Constant::create(ov::element::i64, {2}, {1, 1}), n_seqs,
                             ov::op::v0::Constant::create(ov::element::i64, {1}, {-1})},
            0);
        return std::make_shared<ov::op::v1::Reshape>(part, target, false);
    }

    // Integer router views can share these strides when their row count is zero.
    // Packed projections can store query and gate in separate halves of each head.
    if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) {
        const auto source = context.get_view_input_src_ggml_shape(input_index, 0);
        const auto view = context.get_view_input_ggml_shape(input_index, 0);
        const auto source_stride = context.get_view_input_src_stride(input_index, 0);
        const auto view_stride = context.get_view_input_stride(input_index, 0);
        if (source.size() == 4 && view.size() == 4 && source_stride.size() == 4 && view_stride.size() == 4 &&
            source[0] == 1 && source[1] == 1 && view[0] == 1 && view[1] == source[2] &&
            view[2] > 0 && view[3] > 0 && source_stride[3] > 0 &&
            view_stride[1] == source_stride[2] && view_stride[3] == source_stride[3] &&
            view_stride[2] % source_stride[3] == 0) {
            const size_t head_width = view_stride[2] / source_stride[3];
            const auto offset = context.get_view_input_offset(input_index, 0);
            const auto source_offset = context.get_view_input_src_offset(input_index, 0);
            if (head_width > view[3] && source[3] % head_width == 0 && source[3] / head_width == view[2] &&
                offset >= source_offset && (offset - source_offset) % source_stride[3] == 0) {
                const size_t begin = (offset - source_offset) / source_stride[3];
                if (begin <= head_width - view[3]) {
                    auto heads = std::make_shared<ov::op::v1::Reshape>(input,
                        ov::op::v0::Constant::create(ov::element::i64, {4},
                            std::vector<int64_t>{1, -1, int64_t(view[2]), int64_t(head_width)}), false);
                    auto part = std::make_shared<ov::op::v8::Slice>(heads,
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {begin}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {begin + view[3]}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
                    return part;
                }
            }
        }
    }

    if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real() &&
        context.has_input("s_copy_active_slot_len")) {
        const auto source = context.get_view_input_src_ggml_shape(input_index, 0);
        const auto view = context.get_view_input_ggml_shape(input_index, 0);
        const auto source_stride = context.get_view_input_src_stride(input_index, 0);
        const auto view_stride = context.get_view_input_stride(input_index, 0);
        if (source.size() == 4 && view.size() == 4 && source_stride.size() == 4 && view_stride.size() == 4 &&
            source[0] == 1 && view[0] == source[1] && view[1] == source[2] && view[3] > 0 &&
            view[2] <= source[3] / view[3] &&
            view_stride[0] == source_stride[1] && view_stride[1] == source_stride[2] &&
            view_stride[3] == source_stride[3]) {
            const auto offset = context.get_view_input_offset(input_index, 0);
            const auto source_offset = context.get_view_input_src_offset(input_index, 0);
            if (offset >= source_offset && source_stride[3] > 0 &&
                (offset - source_offset) % source_stride[3] == 0) {
                const int64_t begin = (offset - source_offset) / source_stride[3];
                const int64_t width = view[2] * view[3];
                if (begin <= int64_t(source[3]) - width) {
                    auto sliced = std::make_shared<ov::op::v8::Slice>(input,
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {begin}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {begin + width}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
                    auto prefix = std::make_shared<ov::op::v8::Gather>(
                        std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64),
                        ov::op::v0::Constant::create(ov::element::i64, {2}, {1, 2}),
                        ov::op::v0::Constant::create(ov::element::i64, {}, {0}));
                    auto shape = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{prefix,
                        ov::op::v0::Constant::create(ov::element::i64, {2},
                            std::vector<int64_t>{int64_t(view[2]), int64_t(view[3])})}, 0);
                    return std::make_shared<ov::op::v1::Reshape>(sliced, shape, false);
                }
            }
        }
    }

    // A VIEW that regroups one contiguous span of every source row, e.g. the z/x/B/C splits of the
    // fused mamba projections: [head_dim, n_head, nt, ns] over [d_in_proj, nt, ns] rows. The span
    // dims are packed and the remaining dims carry the source's outer strides, so the view is a
    // Slice of the source's innermost axis plus a Reshape.
    if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) {
        const auto source = context.get_view_input_src_ggml_shape(input_index, 0);
        const auto view = context.get_view_input_ggml_shape(input_index, 0);
        const auto source_stride = context.get_view_input_src_stride(input_index, 0);
        const auto view_stride = context.get_view_input_stride(input_index, 0);
        const auto in_rank = input.get_partial_shape().rank();
        const size_t nd = view.size();
        if (nd == 4 && source.size() == nd && view_stride.size() == nd && source_stride.size() == nd &&
            in_rank.is_static() && in_rank.get_length() == static_cast<int64_t>(nd) &&
            view_stride[nd - 1] == source_stride[nd - 1] && source_stride[nd - 1] > 0) {
            const size_t es = source_stride[nd - 1];
            int j = static_cast<int>(nd) - 1;
            size_t span = 1;
            while (j >= 0 && view_stride[j] == span * es) {
                span *= view[j];
                --j;
            }
            // at least two packed dims replace the source's innermost dim; a one-dim span keeps the
            // source rank and is handled by the generic paths below
            const int shift = static_cast<int>(nd) - 2 - j;
            bool matches = j >= 0 && shift >= 1;
            for (int t = 0; matches && t <= j; ++t) {
                matches = view[t] == source[t + shift] && view_stride[t] == source_stride[t + shift];
            }
            for (int t = 0; matches && t < shift; ++t) {
                matches = source[t] == 1;
            }
            const size_t offset = context.get_view_input_offset(input_index, 0);
            const size_t src_offset = context.get_view_input_src_offset(input_index, 0);
            if (matches && offset >= src_offset && (offset - src_offset) % es == 0) {
                const int64_t begin = static_cast<int64_t>((offset - src_offset) / es);
                if (begin + static_cast<int64_t>(span) <= static_cast<int64_t>(source[nd - 1])) {
                    auto sliced = std::make_shared<ov::op::v8::Slice>(
                        input, ov::op::v0::Constant::create(ov::element::i64, {1}, {begin}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {begin + static_cast<int64_t>(span)}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {static_cast<int64_t>(nd) - 1}));
                    const auto view_ov_shape = context.get_view_input_ov_shape(input_index, 0);
                    std::vector<int64_t> pattern(nd);
                    size_t dynamic_dims = 0;
                    for (size_t i = 0; i < nd; ++i) {
                        if (view_ov_shape.rank().is_static() && view_ov_shape[i].is_static()) {
                            pattern[i] = view_ov_shape[i].get_length();
                        } else {
                            pattern[i] = -1;
                            ++dynamic_dims;
                        }
                    }
                    if (dynamic_dims > 1) {
                        for (size_t i = 0; i < nd; ++i) {
                            pattern[i] = static_cast<int64_t>(view[i]);
                        }
                    }
                    return std::make_shared<ov::op::v1::Reshape>(
                        sliced, ov::op::v0::Constant::create(ov::element::i64, {nd}, pattern), false);
                }
            }
        }
    }

    // A row range of a 2D weight (BERT's token type row): slice the rows of the [rows, row_size] Constant
    if (view_input_size == 1 && input.get_partial_shape().rank().is_static() &&
        input.get_partial_shape().rank().get_length() == 2 &&
        ov::is_type<ov::op::v0::Constant>(input.get_node_shared_ptr())) {
        const auto view = context.get_view_input_ggml_shape(input_index, 0);
        const auto source = context.get_view_input_src_ggml_shape(input_index, 0);
        const auto view_stride = context.get_view_input_stride(input_index, 0);
        const auto source_stride = context.get_view_input_src_stride(input_index, 0);
        const size_t offset = context.get_view_input_offset(input_index, 0);
        const size_t source_offset = context.get_view_input_src_offset(input_index, 0);
        if (view.size() == 4 && source.size() == 4 && view[0] == 1 && view[1] == 1 && view[3] == source[3] &&
            view_stride.size() == 4 && source_stride.size() == 4 && view_stride[2] == source_stride[2] &&
            source_stride[2] > 0 && offset >= source_offset && (offset - source_offset) % source_stride[2] == 0) {
            const int64_t begin = (offset - source_offset) / source_stride[2];
            if (begin + int64_t(view[2]) <= int64_t(source[2])) {
                return std::make_shared<ov::op::v8::Slice>(
                    input, ov::op::v0::Constant::create(ov::element::i64, {1}, {begin}),
                    ov::op::v0::Constant::create(ov::element::i64, {1}, {begin + int64_t(view[2])}),
                    ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
                    ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
            }
        }
    }

    // If translate_view already resolved this VIEW (produced a Slice), the input
    // will already have the expected shape — skip re-slicing.
    //
    // Two notions of "matches" are accepted per axis:
    //   - both dims static and equal, OR
    //   - both dims dynamic.
    // The dynamic case matters for the MoE expert-plane views: translate_view now emits a
    // DYNAMIC-token slice (so the token dim is not frozen). An all-static-only check would
    // see the dynamic token dim, decide the shapes "don't match", and fall through to
    // re-slice/flatten the already-resolved view (a Reshape to the full flattened
    // n_expert_used*n_embd tail, which then conflicts with the single-plane input). Treat a
    // dynamic-vs-dynamic axis as matching so the already-resolved view is reused as-is.
    //
    // A third case matters for split-model MoE fragments: translate_view resolves the
    // expert-plane view against the fragment's INPUT parameter. When the graph is split
    // the token axis of that parameter may already be concrete (static n_tokens) even
    // though get_view_input_ov_shape() still reports it as dynamic (-1). The resolved
    // view is then static [1,1,n_tokens,n_embd] while `expected` is [1,1,?,n_embd].
    // An "expected dynamic, actual static" axis is a valid concretization of the SAME
    // resolved view, so treat it as matching too. Falling through to process_single_view
    // here would re-slice/re-flatten the already-resolved single-plane view against the
    // recorded (multi-plane) source strides and emit a constant-target Reshape whose baked
    // dims no longer divide the concretized input -> "dimensions do not evenly divide".
    // A fourth case matters for stateful execution: `expected` comes from ggml metadata and is
    // always GGML_MAX_DIMS ranks, but stateful drops the leading size-1 batch dim, so the
    // resolved view is one rank lower. Compare the common trailing dims and require the
    // leading expected dims we skip to be 1. Without this the rank test below never matches on
    // the stateful path and every already-resolved MoE expert-plane view is re-sliced.
    auto expected_ov_shape = context.get_view_input_ov_shape(input_index, 0);
    auto actual_shape = input.get_partial_shape();
    if (expected_ov_shape.rank().is_static() && actual_shape.rank().is_static() &&
        expected_ov_shape.rank().get_length() >= actual_shape.rank().get_length()) {
        const int64_t n_actual = actual_shape.rank().get_length();
        const int64_t shift = expected_ov_shape.rank().get_length() - n_actual;
        bool shapes_match = true;
        for (int64_t i = 0; i < shift; ++i) {
            if (!expected_ov_shape[i].is_static() || expected_ov_shape[i].get_length() != 1) {
                shapes_match = false;
                break;
            }
        }
        for (int64_t i = 0; i < n_actual && shapes_match; ++i) {
            const auto & exp = expected_ov_shape[i + shift];
            const bool both_dynamic = exp.is_dynamic() && actual_shape[i].is_dynamic();
            const bool both_static_equal =
                exp.is_static() && actual_shape[i].is_static() && exp == actual_shape[i];
            // expected dynamic, actual static: the resolved view already carries the
            // concrete size for this fragment; reuse it rather than re-materializing.
            const bool expected_dyn_actual_static = exp.is_dynamic() && actual_shape[i].is_static();
            if (!both_dynamic && !both_static_equal && !expected_dyn_actual_static) {
                shapes_match = false;
                break;
            }
        }
        if (shapes_match) {
            return input;
        }
    }

    // In static mode, use Split instead of Slice for single-dimension reductions.
    // This ensures NPUW's FOLD doesn't parametrize per-layer slice indices (which
    // would introduce dynamic shapes). A shared Split node sits outside the repeated
    // subgraph boundary; each layer receives one of its output ports.
    // The dynamic GPU path uses it too: a StridedSlice costs a full shape inference per run on GPU, a Split output does
    // not (gemma-4 slices its per-layer embeddings this way, once per layer)
    const bool dynamic_split = !context.is_static() && ggml_openvino_is_gpu();
    if ((context.is_static() || dynamic_split) && view_input_size == 1) {
        auto view_stride_v = context.get_view_input_stride(input_index, 0);
        auto view_src_stride_v = context.get_view_input_src_stride(input_index, 0);
        auto view_ggml_shape = context.get_view_input_ggml_shape(input_index, 0);
        auto view_src_ggml_shape = context.get_view_input_src_ggml_shape(input_index, 0);
        auto view_offset = context.get_view_input_offset(input_index, 0);
        auto view_src_offset = context.get_view_input_src_offset(input_index, 0);

        size_t ndims = view_ggml_shape.size();
        std::vector<int> diff_dims;
        if (view_src_ggml_shape.size() == ndims) {
            for (size_t i = 0; i < ndims; ++i) {
                if (view_ggml_shape[i] != view_src_ggml_shape[i]) {
                    diff_dims.push_back(static_cast<int>(i));
                }
            }
        }

        if (diff_dims.size() == 1) {
            int split_dim = diff_dims[0];
            int64_t num_splits = static_cast<int64_t>(view_src_ggml_shape[split_dim]);
            int64_t chunk_size = static_cast<int64_t>(view_ggml_shape[split_dim]);

            // Only apply when slicing exactly 1 element from a multi-element dimension
            if (chunk_size == 1 && num_splits > 1) {
                // Check suffix strides match (dimensions after split_dim)
                bool suffix_ok = view_stride_v.size() == view_src_stride_v.size();
                if (suffix_ok) {
                    for (size_t i = static_cast<size_t>(split_dim) + 1; i < ndims; ++i) {
                        if (view_stride_v[i] != view_src_stride_v[i]) {
                            suffix_ok = false;
                            break;
                        }
                    }
                }

                if (suffix_ok && view_src_stride_v[split_dim] > 0) {
                    size_t relative_offset = view_offset >= view_src_offset ? view_offset - view_src_offset : 0;
                    int64_t split_index = static_cast<int64_t>(relative_offset / view_src_stride_v[split_dim]);

                    // the view must be exactly one Split output: offset on a chunk boundary, the strides of all
                    // other dims with more than one element equal
                    bool exact_chunk = relative_offset % view_src_stride_v[split_dim] == 0;
                    for (size_t i = 0; i < ndims && exact_chunk; ++i) {
                        exact_chunk = i == static_cast<size_t>(split_dim) || view_ggml_shape[i] == 1 ||
                                      view_stride_v[i] == view_src_stride_v[i];
                    }
                    // num_splits is the captured source size: on a dynamic axis (e.g. the token axis of DSpark's
                    // result_norm, read one block position at a time) the graph is reused with other sizes, and
                    // each Split output would then hold several rows or the wrong one
                    const auto input_shape = input.get_partial_shape();
                    const int64_t split_axis = input_shape.rank().is_static() ?
                                                   split_dim - (int64_t) ndims + input_shape.rank().get_length() :
                                                   -1;
                    const bool split_axis_static = split_axis >= 0 && input_shape[split_axis].is_static() &&
                                                   input_shape[split_axis].get_length() == num_splits;
                    if (split_index >= 0 && split_index < num_splits && dynamic_split && exact_chunk &&
                        split_axis_static) {
                        // the Split keeps its input alive, so only keep a weak reference to it on the input
                        auto src_node = input.get_node_shared_ptr();
                        std::string rt_key =
                            "split_dim_weak_" + std::to_string(split_dim) + "_" + std::to_string(input.get_index());
                        auto & rt_info = src_node->get_rt_info();
                        std::shared_ptr<ov::Node> split_node;
                        if (rt_info.count(rt_key) != 0) {
                            split_node = rt_info[rt_key].as<std::weak_ptr<ov::Node>>().lock();
                        }
                        if (split_node == nullptr) {
                            auto axis_const = ov::op::v0::Constant::create(ov::element::i64, {}, {split_axis});
                            split_node =
                                std::make_shared<ov::op::v1::Split>(input, axis_const, static_cast<size_t>(num_splits));
                            split_node->set_friendly_name(src_node->get_friendly_name() + "_split");
                            rt_info[rt_key] = std::weak_ptr<ov::Node>(split_node);
                        }
                        return split_node->output(static_cast<size_t>(split_index));
                    }
                    if (split_index >= 0 && split_index < num_splits && !dynamic_split) {
                        // as above: a weak reference, and one Split per output port
                        auto src_node = input.get_node_shared_ptr();
                        std::string rt_key =
                            "split_dim_static_" + std::to_string(split_dim) + "_" + std::to_string(input.get_index());
                        auto & rt_info = src_node->get_rt_info();
                        std::shared_ptr<ov::Node> split_node;
                        if (rt_info.count(rt_key) != 0) {
                            split_node = rt_info[rt_key].as<std::weak_ptr<ov::Node>>().lock();
                        }
                        if (split_node == nullptr) {
                            auto axis_const =
                                ov::op::v0::Constant::create(ov::element::i64, {}, {static_cast<int64_t>(split_dim)});
                            split_node =
                                std::make_shared<ov::op::v1::Split>(input, axis_const, static_cast<size_t>(num_splits));
                            split_node->set_friendly_name(src_node->get_friendly_name() + "_split");
                            rt_info[rt_key] = std::weak_ptr<ov::Node>(split_node);
                        }
                        return split_node->output(static_cast<size_t>(split_index));
                    }
                }
            }
        }
    }

    // Lambda function to process a single view operation
    auto process_single_view =
        [is_static = context.is_static()](
           ov::Output<ov::Node> current, size_t view_offset, const std::vector<size_t> & view_stride,
           const ov::Shape & view_ggml_shape, const ov::PartialShape & view_ov_shape, const std::string & view_name,
           size_t view_src_offset, const std::vector<size_t> & view_src_stride, const ov::Shape & view_src_ggml_shape,
           const ov::PartialShape & view_src_ov_shape, const std::string & view_src_name) -> ov::Output<ov::Node> {
        // Stateful execution drops a leading size-1 axis, so `current` can be one rank lower
        // than the ggml shape metadata (view_stride/view_ggml_shape, always GGML_MAX_DIMS
        // entries) assumes. Shift any axis index built from that metadata down by the
        // difference before using it as an OV Slice axis.
        const auto current_rank = current.get_partial_shape().rank();
        const int axis_shift = current_rank.is_static() ?
                                    static_cast<int>(view_stride.size()) - static_cast<int>(current_rank.get_length()) :
                                    0;

        auto build_reshape_pattern = [](const ov::PartialShape & target_ov_shape,
                                        const ov::Shape & target_ggml_shape) -> std::vector<int64_t> {
            const size_t ndims = target_ggml_shape.size();
            std::vector<int64_t> reshape_pattern(ndims);
            size_t dynamic_dims = 0;

            if (target_ov_shape.rank().is_static() &&
                target_ov_shape.rank().get_length() == static_cast<int64_t>(ndims)) {
                for (size_t i = 0; i < ndims; ++i) {
                    if (target_ov_shape[i].is_static()) {
                        reshape_pattern[i] = target_ov_shape[i].get_length();
                    } else {
                        reshape_pattern[i] = -1;
                        ++dynamic_dims;
                    }
                }
            } else {
                dynamic_dims = 2;
            }

            if (dynamic_dims > 1) {
                for (size_t i = 0; i < ndims; ++i) {
                    reshape_pattern[i] = static_cast<int64_t>(target_ggml_shape[i]);
                }
            }

            return reshape_pattern;
        };

        auto build_prefix_tail_reshape_pattern = [](const ov::PartialShape & target_ov_shape,
                                                    const ov::Shape & target_ggml_shape, size_t prefix_dims,
                                                    int64_t tail_dim) -> std::vector<int64_t> {
            std::vector<int64_t> reshape_pattern(prefix_dims + 1);
            size_t dynamic_dims = 0;

            if (target_ov_shape.rank().is_static() &&
                target_ov_shape.rank().get_length() == static_cast<int64_t>(target_ggml_shape.size())) {
                for (size_t i = 0; i < prefix_dims; ++i) {
                    if (target_ov_shape[i].is_static()) {
                        reshape_pattern[i] = target_ov_shape[i].get_length();
                    } else {
                        reshape_pattern[i] = -1;
                        ++dynamic_dims;
                    }
                }
            } else {
                dynamic_dims = 2;
            }

            if (dynamic_dims > 1) {
                for (size_t i = 0; i < prefix_dims; ++i) {
                    reshape_pattern[i] = static_cast<int64_t>(target_ggml_shape[i]);
                }
            }

            reshape_pattern[prefix_dims] = tail_dim;
            return reshape_pattern;
        };

        bool same_stride = view_stride.size() == view_src_stride.size();
        if (same_stride) {
            for (size_t i = 0; i < view_stride.size(); ++i) {
                if (view_stride[i] != view_src_stride[i]) {
                    same_stride = false;
                    break;
                }
            }
        }

        bool same_ggml_shape = view_ggml_shape.size() == view_src_ggml_shape.size();
        if (same_ggml_shape) {
            for (size_t i = 0; i < view_ggml_shape.size(); ++i) {
                if (view_ggml_shape[i] != view_src_ggml_shape[i]) {
                    same_ggml_shape = false;
                    break;
                }
            }
        }

        if (same_stride && same_ggml_shape) {
            return current;
        }

        if (same_stride) {
            const size_t relative_offset = view_offset >= view_src_offset ? view_offset - view_src_offset : 0;
            const size_t ndims = view_stride.size();

            std::vector<int> diff_dims;
            if (view_ggml_shape.size() == ndims && view_src_ggml_shape.size() == ndims) {
                for (size_t i = 0; i < ndims; ++i) {
                    if (view_ggml_shape[i] != view_src_ggml_shape[i]) {
                        diff_dims.push_back(static_cast<int>(i));
                    }
                }
            }

            if (diff_dims.size() == 1) {
                const int slice_dim = diff_dims[0];
                const int64_t dim_size = static_cast<int64_t>(view_src_ggml_shape[slice_dim]);

                if (view_stride[slice_dim] > 0 && relative_offset % view_stride[slice_dim] == 0) {
                    const int64_t begin_val = static_cast<int64_t>((relative_offset / view_stride[slice_dim]) %
                                                                   static_cast<size_t>(dim_size));
                    const int64_t end_val = begin_val + static_cast<int64_t>(view_ggml_shape[slice_dim]);

                    if (begin_val >= 0 && end_val <= dim_size) {
                        auto sliced = std::make_shared<ov::op::v8::Slice>(
                            current, ov::op::v0::Constant::create(ov::element::i64, {1}, {begin_val}),
                            ov::op::v0::Constant::create(ov::element::i64, {1}, {end_val}),
                            ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
                            ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_dim - axis_shift}));

                        // In a static graph a rank-preserving slice (diff_dims has one entry) already has the view
                        // shape. Skip the Reshape: its target bakes the static chunk size into the token axis, which
                        // is wrong after the output-ids GET_ROWS of the last layer (1 token in the prefill graph).
                        const bool rank_kept = is_static && current_rank.is_static() &&
                                               static_cast<size_t>(current_rank.get_length()) == ndims;
                        if (view_ov_shape.is_static() && !rank_kept) {
                            auto reshaped = std::make_shared<ov::op::v1::Reshape>(
                                sliced,
                                ov::op::v0::Constant::create(ov::element::i64, {ndims}, view_ov_shape.to_shape()),
                                false);
                            reshaped->set_friendly_name(view_name);
                            return reshaped;
                        }

                        sliced->set_friendly_name(view_name);
                        return sliced;
                    }
                }

                int64_t tail_src_elems = 1;
                int64_t tail_dst_elems = 1;
                for (size_t i = slice_dim; i < ndims; ++i) {
                    tail_src_elems *= static_cast<int64_t>(view_src_ggml_shape[i]);
                    tail_dst_elems *= static_cast<int64_t>(view_ggml_shape[i]);
                }

                const size_t elem_stride = view_stride[ndims - 1];
                int64_t tail_begin = 0;
                if (elem_stride > 0) {
                    tail_begin =
                        static_cast<int64_t>((relative_offset / elem_stride) % static_cast<size_t>(tail_src_elems));
                }
                const int64_t tail_end = tail_begin + tail_dst_elems;

                if (tail_begin >= 0 && tail_end <= tail_src_elems) {
                    std::vector<int64_t> flat_shape;
                    flat_shape.reserve(slice_dim);
                    for (int i = 0; i < slice_dim; ++i) {
                        flat_shape.push_back(static_cast<int64_t>(view_src_ggml_shape[i]));
                    }
                    flat_shape.push_back(tail_src_elems);
                    const size_t flat_ndims = flat_shape.size();

                    auto flat = std::make_shared<ov::op::v1::Reshape>(
                        current, ov::op::v0::Constant::create(ov::element::i64, {flat_ndims}, flat_shape), false);

                    auto sliced = std::make_shared<ov::op::v8::Slice>(
                        flat, ov::op::v0::Constant::create(ov::element::i64, {1}, {tail_begin}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {tail_end}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
                        ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_dim}));

                    if (view_ov_shape.is_static()) {
                        auto reshaped = std::make_shared<ov::op::v1::Reshape>(
                            sliced, ov::op::v0::Constant::create(ov::element::i64, {ndims}, view_ov_shape.to_shape()),
                            false);
                        reshaped->set_friendly_name(view_name);
                        return reshaped;
                    }

                    sliced->set_friendly_name(view_name);
                    return sliced;
                }
            }

            std::vector<int64_t> begin(ndims, 0);
            std::vector<int64_t> end(ndims, 0);
            std::vector<int64_t> step(ndims, 1);
            std::vector<int64_t> axes(ndims, 0);

            size_t remaining_offset = relative_offset;
            for (size_t i = 0; i < ndims; ++i) {
                axes[i] = static_cast<int64_t>(i);
                if (view_stride[i] > 0) {
                    begin[i] = static_cast<int64_t>(remaining_offset / view_stride[i]);
                    remaining_offset %= view_stride[i];
                }
                end[i] = begin[i] + static_cast<int64_t>(view_ggml_shape[i]);
            }

            bool in_bounds = view_src_ggml_shape.size() == ndims && view_ggml_shape.size() == ndims;
            if (in_bounds) {
                for (size_t i = 0; i < ndims; ++i) {
                    if (end[i] > static_cast<int64_t>(view_src_ggml_shape[i])) {
                        in_bounds = false;
                        break;
                    }
                }
            }

            if (in_bounds && remaining_offset == 0) {
                auto sliced = std::make_shared<ov::op::v8::Slice>(
                    current, ov::op::v0::Constant::create(ov::element::i64, {ndims}, begin),
                    ov::op::v0::Constant::create(ov::element::i64, {ndims}, end),
                    ov::op::v0::Constant::create(ov::element::i64, {ndims}, step),
                    ov::op::v0::Constant::create(ov::element::i64, {ndims}, axes));

                sliced->set_friendly_name(view_name);
                return sliced;
            }
        } else {
            bool same_rank = view_stride.size() == view_src_stride.size() &&
                             view_ggml_shape.size() == view_src_ggml_shape.size() &&
                             view_stride.size() == view_ggml_shape.size();
            const size_t relative_offset = view_offset >= view_src_offset ? view_offset - view_src_offset : 0;

            if (same_rank) {
                const size_t ndims = view_ggml_shape.size();
                std::vector<int> diff_dims;
                for (size_t i = 0; i < ndims; ++i) {
                    if (view_ggml_shape[i] != view_src_ggml_shape[i]) {
                        diff_dims.push_back(static_cast<int>(i));
                    }
                }

                if (diff_dims.size() == 1) {
                    const size_t slice_dim = static_cast<size_t>(diff_dims[0]);
                    bool suffix_stride_match = true;
                    for (size_t i = slice_dim + 1; i < ndims; ++i) {
                        if (view_stride[i] != view_src_stride[i]) {
                            suffix_stride_match = false;
                            break;
                        }
                    }

                    if (suffix_stride_match && view_src_stride[slice_dim] > 0 &&
                        relative_offset % view_src_stride[slice_dim] == 0) {
                        const int64_t begin_val = static_cast<int64_t>(relative_offset / view_src_stride[slice_dim]);
                        const int64_t end_val = begin_val + static_cast<int64_t>(view_ggml_shape[slice_dim]);
                        const int64_t dim_size = static_cast<int64_t>(view_src_ggml_shape[slice_dim]);

                        if (begin_val >= 0 && end_val <= dim_size) {
                            auto sliced = std::make_shared<ov::op::v8::Slice>(
                                current, ov::op::v0::Constant::create(ov::element::i64, {1}, {begin_val}),
                                ov::op::v0::Constant::create(ov::element::i64, {1}, {end_val}),
                                ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
                                ov::op::v0::Constant::create(ov::element::i64, {1}, {static_cast<int64_t>(slice_dim)}));
                            sliced->set_friendly_name(view_name);
                            return sliced;
                        }
                    }
                }
            }

            // A view that reads the first cells of a single-sequence cache [1, 1, cells, row] with each cell one whole
            // row, e.g. MLA's K view [1, n_kv, 1 (n_head_kv), 576]. With the cache input sliced to the cells in use,
            // this is a reshape that keeps the cell axis dynamic.
            if (same_rank && relative_offset == 0 && view_ggml_shape.size() >= 2 && view_ov_shape.rank().is_static() &&
                view_ov_shape.rank().get_length() == static_cast<int64_t>(view_ggml_shape.size()) &&
                current.get_partial_shape().rank().is_static() &&
                current.get_partial_shape().rank().get_length() == static_cast<int64_t>(view_ggml_shape.size())) {
                const size_t ndims = view_ggml_shape.size();
                const size_t row_stride = view_src_stride[ndims - 2];
                bool src_rows = view_src_stride[ndims - 1] == view_stride[ndims - 1];
                for (size_t i = 0; i + 2 < ndims && src_rows; ++i) {
                    src_rows = view_src_ggml_shape[i] == 1;
                }
                int cell_axis = -1;
                for (size_t i = 0; i < ndims && src_rows; ++i) {
                    if (view_stride[i] == row_stride && view_ov_shape[i].is_dynamic()) {
                        cell_axis = static_cast<int>(i);
                    }
                }
                bool one_row_per_cell = cell_axis >= 0;
                size_t inner_bytes = view_stride[ndims - 1];
                for (size_t i = 0; i < ndims && one_row_per_cell; ++i) {
                    if (static_cast<int>(i) < cell_axis) {
                        one_row_per_cell = view_ggml_shape[i] == 1;
                    } else if (static_cast<int>(i) > cell_axis) {
                        inner_bytes *= view_ggml_shape[i];
                    }
                }
                if (one_row_per_cell && inner_bytes == row_stride) {
                    auto reshape_pattern = build_reshape_pattern(view_ov_shape, view_ggml_shape);
                    auto reshaped = std::make_shared<ov::op::v1::Reshape>(
                        current,
                        ov::op::v0::Constant::create(ov::element::i64, {reshape_pattern.size()}, reshape_pattern),
                        false);
                    reshaped->set_friendly_name(view_name);
                    return reshaped;
                }
            }

            size_t view_elems = 1;
            size_t src_elems = 1;
            if (same_rank) {
                for (size_t i = 0; i < view_ggml_shape.size(); ++i) {
                    view_elems *= view_ggml_shape[i];
                    src_elems *= view_src_ggml_shape[i];
                }
            }

            bool same_num_elements = same_rank && view_elems == src_elems;

            if (same_rank && relative_offset == 0 && same_num_elements) {
                auto reshape_pattern = build_reshape_pattern(view_ov_shape, view_ggml_shape);

                auto reshaped = std::make_shared<ov::op::v1::Reshape>(
                    current, ov::op::v0::Constant::create(ov::element::i64, {reshape_pattern.size()}, reshape_pattern),
                    false);
                reshaped->set_friendly_name(view_name);
                return reshaped;
            }

            if (same_rank) {
                const size_t ndims = view_ggml_shape.size();

                // Match views that can be expressed as a regular strided slice over the
                // already reconstructed source tensor, e.g. offset on one axis plus step > 1
                // on another axis.
                bool is_regular_slice = view_src_ggml_shape.size() == ndims;
                std::vector<int64_t> begin(ndims, 0);
                std::vector<int64_t> end(ndims, 0);
                std::vector<int64_t> step(ndims, 1);
                std::vector<int64_t> axes(ndims, 0);
                size_t remaining_offset = relative_offset;

                if (is_regular_slice) {
                    for (size_t i = 0; i < ndims; ++i) {
                        axes[i] = static_cast<int64_t>(i);

                        if (view_src_stride[i] == 0 || view_stride[i] == 0 ||
                            view_stride[i] % view_src_stride[i] != 0) {
                            is_regular_slice = false;
                            break;
                        }

                        step[i] = static_cast<int64_t>(view_stride[i] / view_src_stride[i]);
                        if (step[i] <= 0) {
                            is_regular_slice = false;
                            break;
                        }

                        begin[i] = static_cast<int64_t>(remaining_offset / view_src_stride[i]);
                        remaining_offset %= view_src_stride[i];

                        if (view_ggml_shape[i] == 0) {
                            end[i] = begin[i];
                            continue;
                        }

                        end[i] = begin[i] + step[i] * static_cast<int64_t>(view_ggml_shape[i] - 1) + 1;

                        if (begin[i] < 0 || end[i] > static_cast<int64_t>(view_src_ggml_shape[i])) {
                            is_regular_slice = false;
                            break;
                        }
                    }
                }

                if (is_regular_slice && remaining_offset == 0) {
                    auto sliced = std::make_shared<ov::op::v8::Slice>(
                        current, ov::op::v0::Constant::create(ov::element::i64, {ndims}, begin),
                        ov::op::v0::Constant::create(ov::element::i64, {ndims}, end),
                        ov::op::v0::Constant::create(ov::element::i64, {ndims}, step),
                        ov::op::v0::Constant::create(ov::element::i64, {ndims}, axes));

                    sliced->set_friendly_name(view_name);
                    return sliced;
                }

                const size_t elem_stride = view_src_stride.back();
                const bool aligned_offset = elem_stride > 0 && relative_offset % elem_stride == 0;

                if (aligned_offset) {
                    size_t suffix_start = 0;
                    size_t expected_stride = elem_stride;
                    for (int i = static_cast<int>(ndims) - 1; i >= 0; --i) {
                        if (view_stride[i] != expected_stride) {
                            suffix_start = static_cast<size_t>(i + 1);
                            break;
                        }
                        expected_stride *= view_ggml_shape[i];
                    }

                    size_t prefix_elems = 1;
                    size_t suffix_elems = 1;
                    for (size_t i = 0; i < suffix_start; ++i) {
                        prefix_elems *= view_ggml_shape[i];
                    }
                    for (size_t i = suffix_start; i < ndims; ++i) {
                        suffix_elems *= view_ggml_shape[i];
                    }

                    if (prefix_elems > 0 && src_elems % prefix_elems == 0) {
                        const size_t src_tail_elems = src_elems / prefix_elems;
                        const int64_t tail_begin = static_cast<int64_t>(relative_offset / elem_stride);
                        const int64_t tail_end = tail_begin + static_cast<int64_t>(suffix_elems);

                        if (tail_begin >= 0 && tail_end <= static_cast<int64_t>(src_tail_elems)) {
                            auto prefix_tail_pattern = build_prefix_tail_reshape_pattern(
                                view_ov_shape, view_ggml_shape, suffix_start, static_cast<int64_t>(src_tail_elems));

                            auto prefix_tail = std::make_shared<ov::op::v1::Reshape>(
                                current,
                                ov::op::v0::Constant::create(ov::element::i64, {prefix_tail_pattern.size()},
                                                             prefix_tail_pattern),
                                false);

                            ov::Output<ov::Node> selected = prefix_tail;
                            if (tail_begin != 0 || tail_end != static_cast<int64_t>(src_tail_elems)) {
                                selected = std::make_shared<ov::op::v8::Slice>(
                                    prefix_tail, ov::op::v0::Constant::create(ov::element::i64, {1}, {tail_begin}),
                                    ov::op::v0::Constant::create(ov::element::i64, {1}, {tail_end}),
                                    ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
                                    ov::op::v0::Constant::create(ov::element::i64, {1},
                                                                 {static_cast<int64_t>(suffix_start)}));
                            }

                            auto reshape_pattern = build_reshape_pattern(view_ov_shape, view_ggml_shape);
                            auto reshaped = std::make_shared<ov::op::v1::Reshape>(
                                selected,
                                ov::op::v0::Constant::create(ov::element::i64, {reshape_pattern.size()},
                                                             reshape_pattern),
                                false);
                            reshaped->set_friendly_name(view_name);
                            return reshaped;
                        }
                    }
                }
            }

            return current;
        }

        (void) view_name;
        (void) view_src_ov_shape;
        (void) view_src_name;

        return current;
    };

    // Special case: ggml collapses VIEW-of-VIEW chains so that `view_offs` is always an
    // ABSOLUTE offset from the true root allocation, regardless of how many VIEW levels
    // are in between (see ggml_new_tensor_impl). `src[0]` is still the immediate op-graph
    // parent though, which can be a DIFFERENT (already narrowed) VIEW with the SAME ggml
    // shape as this one but a different absolute offset -- e.g. a per-layer deepstack
    // slice `view_2d(embd, n_embd, n_tokens, embd->nb[1], layer*n_embd*sizeof(float))`
    // whose src[0] ("embd") is itself already a zero-offset VIEW of the true root (the
    // padded embedding). Chaining through "embd" here would try to re-slice an already
    // 2-narrowed tensor using a root-relative offset, going out of bounds and silently
    // falling back to a no-op (returning the wrong, already-resolved sibling slice).
    // Detect this (same shape as the immediate src, but different absolute offset) and
    // re-slice directly from the untouched root using the innermost view's absolute
    // offset against the ROOT's own shape/stride instead of chaining through src[0].
    {
        auto innermost_offset = context.get_view_input_offset(input_index, 0);
        auto innermost_src_offset = context.get_view_input_src_offset(input_index, 0);
        auto innermost_shape = context.get_view_input_ggml_shape(input_index, 0);
        auto innermost_src_shape = context.get_view_input_src_ggml_shape(input_index, 0);
        if (innermost_offset != innermost_src_offset && innermost_shape == innermost_src_shape) {
            size_t root_view_idx = view_input_size - 1;
            auto root_ggml_shape = context.get_view_input_src_ggml_shape(input_index, root_view_idx);
            auto root_stride = context.get_view_input_src_stride(input_index, root_view_idx);
            auto root_offset = context.get_view_input_src_offset(input_index, root_view_idx);
            auto root_ov_shape = context.get_view_input_src_ov_shape(input_index, root_view_idx);
            auto root_name = context.get_view_input_src_name(input_index, root_view_idx);
            auto innermost_stride = context.get_view_input_stride(input_index, 0);
            auto innermost_ov_shape = context.get_view_input_ov_shape(input_index, 0);
            auto innermost_name = context.get_view_input_name(input_index, 0);

            return process_single_view(input, innermost_offset, innermost_stride, innermost_shape, innermost_ov_shape,
                                       innermost_name, root_offset, root_stride, root_ggml_shape, root_ov_shape,
                                       root_name);
        }
    }

    // Process views from the base tensor (last) to the current view (first)
    // Start with the base tensor
    ov::Output<ov::Node> current = input;

    // Process each view in reverse order (from base to current)
    for (int view_idx = view_input_size - 1; view_idx >= 0; view_idx--) {
        auto view_offset = context.get_view_input_offset(input_index, view_idx);
        auto view_stride = context.get_view_input_stride(input_index, view_idx);
        auto view_ggml_shape = context.get_view_input_ggml_shape(input_index, view_idx);
        auto view_ov_shape = context.get_view_input_ov_shape(input_index, view_idx);
        auto view_name = context.get_view_input_name(input_index, view_idx);

        // print view info
        // std::cout << "View " << view_idx << ": name = " << view_name << ", offset = " << view_offset << ", stride = ["
        //       << view_stride[0] << "," << view_stride[1] << "," << view_stride[2] << "," << view_stride[3]
        //       << "], ggml shape = [" << view_ggml_shape[0] << "," << view_ggml_shape[1] << ","
        //       << view_ggml_shape[2] << "," << view_ggml_shape[3] << "], ov shape = " << view_ov_shape << std::endl;

        auto view_src_offset = context.get_view_input_src_offset(input_index, view_idx);
        auto view_src_stride = context.get_view_input_src_stride(input_index, view_idx);
        auto view_src_ggml_shape = context.get_view_input_src_ggml_shape(input_index, view_idx);
        auto view_src_ov_shape = context.get_view_input_src_ov_shape(input_index, view_idx);
        auto view_src_name = context.get_view_input_src_name(input_index, view_idx);
        // print source view info
        // std::cout << "View " << view_idx << ": source name = " << view_src_name
        //           << ", source offset = " << view_src_offset << ", source stride = [" << view_src_stride[0] << ","
        //           << view_src_stride[1] << "," << view_src_stride[2] << "," << view_src_stride[3]
        //           << "], source ggml shape = [" << view_src_ggml_shape[0] << "," << view_src_ggml_shape[1] << ","
        //           << view_src_ggml_shape[2] << "," << view_src_ggml_shape[3]
        //           << "], source ov shape = " << view_src_ov_shape << std::endl;

        current = process_single_view(current, view_offset, view_stride, view_ggml_shape, view_ov_shape, view_name,
                                      view_src_offset, view_src_stride, view_src_ggml_shape, view_src_ov_shape,
                                      view_src_name);
    }

    return current;
}

bool is_recurrent_cache_reset_case(const NodeContext & context) {
    return context.get_op_case() == 1 && context.has_input("cache_rs_reset_len");
}

OutputVector translate_recurrent_cache_reset(const NodeContext & context) {
    auto cache_rs = context.get_input(0);
    auto cache_rs_reset_idx = context.get_input("cache_rs_reset_idx");
    auto cache_rs_reset_len = context.get_input("cache_rs_reset_len");

    auto cache_shape = std::make_shared<ov::op::v3::ShapeOf>(cache_rs, ov::element::i64);
    auto n_slots_1d = std::make_shared<ov::op::v8::Gather>(
        cache_shape, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}),
        ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));
    auto n_slots = std::make_shared<ov::op::v0::Squeeze>(n_slots_1d);

    auto iota = std::make_shared<ov::op::v4::Range>(
        ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0}), n_slots,
        ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {1}), ov::element::i64);

    auto idx_plus_len = std::make_shared<ov::op::v1::Add>(cache_rs_reset_idx, cache_rs_reset_len);
    auto less_than_idx = std::make_shared<ov::op::v1::Less>(iota, cache_rs_reset_idx);
    auto greater_equal_idx_plus_len = std::make_shared<ov::op::v1::GreaterEqual>(iota, idx_plus_len);
    auto keep_mask = std::make_shared<ov::op::v1::LogicalOr>(less_than_idx, greater_equal_idx_plus_len);
    auto keep_mask_reshape = std::make_shared<ov::op::v0::Unsqueeze>(
        keep_mask, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));

    auto zero = ov::op::v0::Constant::create(cache_rs.get_element_type(), ov::Shape{}, {0});
    auto cleared_cache_rs = std::make_shared<ov::op::v1::Select>(keep_mask_reshape, cache_rs, zero);
    return rename_outputs_with_suffix({cleared_cache_rs}, context.get_name());
}

}  // namespace ggml
}  // namespace frontend
}  // namespace ov