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
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
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
#include "ggml-decoder.h"

#include "ggml-impl.h"
#include "ggml-openvino-extra.h"
#include "ggml-openvino.h"
#include "ggml-quants.h"
#include "ggml.h"
#include "utils.h"

#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <map>
#include <memory>
#include <mutex>
#include <openvino/core/dimension.hpp>
#include <openvino/core/except.hpp>
#include <openvino/core/node.hpp>
#include <openvino/core/partial_shape.hpp>
#include <openvino/core/type/bfloat16.hpp>
#include <openvino/core/type/element_type.hpp>
#include <openvino/core/type/float16.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/convert.hpp>
#include <openvino/runtime/tensor.hpp>
#include <ostream>
#include <set>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>

static std::set<std::string> collect_graph_output_names(const ggml_cgraph * cgraph) {
    std::set<std::string> outputs;
    for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) {
        auto * node = cgraph->nodes[node_n];
        if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
            outputs.insert(node->name);
        }
    }
    return outputs;
}

bool GgmlOvDecoder::has_same_graph_io(const ggml_cgraph * cgraph) const {
    if (m_built_output_names.empty()) {
        return true;  // no snapshot (naive / test decoders): nothing to compare against
    }
    return collect_graph_output_names(cgraph) == m_built_output_names;
}

GgmlOvDecoder::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,
                             bool model_is_splitted,
                             bool is_prefill,
                             int prefill_chunk_size) :
    m_is_static(is_static),
    m_is_stateful(is_stateful),
    m_is_prefill(is_prefill),
    m_naive(false),
    m_prefill_chunk_size(prefill_chunk_size),
    m_model_is_splitted(model_is_splitted),
    m_cgraph(cgraph),
    m_model_weights(model_weights),
    m_model_params(model_params),
    m_compute_params(compute_params) {
    static bool printed_address_map = false;
    if (!printed_address_map) {
        if (ggml_openvino_getenv_int("GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS")) {
            printed_address_map = true;
            print_tensor_address_map(cgraph);
        }
    }

    validate_cgraph();

    m_built_output_names = collect_graph_output_names(cgraph);

    set_input_output();
    compute_node_dynamic_dims();
    compute_model_inputs();
    compute_model_outputs();

    for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) {
        m_node_info_list[node_n].node_op_case = compute_op_case(m_node_info_list[node_n].node);
        m_node_info_list[node_n].node_op_type = compute_op_type(m_node_info_list[node_n].node);
    }

    add_extra_inputs();
}

void GgmlOvDecoder::update_io(ggml_cgraph * cgraph) {
    m_cgraph = cgraph;
    m_built_output_names = collect_graph_output_names(cgraph);
    m_model_inputs.clear();
    m_model_outputs.clear();
    m_node_info_list.clear();
    m_node_dynamic_dims.clear();
    set_input_output();
    compute_node_dynamic_dims();
    compute_model_inputs();
    compute_model_outputs();
    for (int i = 0; i < cgraph->n_nodes; ++i) {
        m_node_info_list[i].node_op_case = compute_op_case(m_node_info_list[i].node);
        m_node_info_list[i].node_op_type = compute_op_type(m_node_info_list[i].node);
    }
}

// llama keeps separate graphs for batches with and without outputs, so a cache hit can come from a
// graph built in other memory. The decoder then still points at the old graph's tensors.
bool GgmlOvDecoder::is_bound_to(const ggml_cgraph * cgraph) const {
    return m_cgraph == cgraph && cgraph->n_nodes > 0 && m_node_info_list.size() == (size_t) cgraph->n_nodes &&
           m_node_info_list.front().node == cgraph->nodes[0] &&
           m_node_info_list.back().node == cgraph->nodes[cgraph->n_nodes - 1];
}

GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, std::map<std::string, std::shared_ptr<ov::Node>> & model_weights) {
    m_cgraph = cgraph;
    m_model_weights = model_weights;
    m_naive = true;
    for (int i = 0; i < cgraph->n_nodes; ++i) {
        if ((cgraph->nodes[i]->op == GGML_OP_GATED_DELTA_NET && cgraph->nodes[i]->op_params[0] > 1) ||
            is_sampling_view(cgraph->nodes[i]) || is_conv_state_snapshot_writeback(cgraph->nodes[i]) ||
            is_ssm_state_writeback(cgraph->nodes[i])) {
            std::tie(m_model_params, m_compute_params) = compute_llm_params(cgraph, false);
            add_extra_inputs();
            break;
        }
    }
    set_input_output();
    compute_model_inputs();
    compute_model_outputs();
    for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) {
        m_node_info_list[node_n].node_op_case = compute_op_case(m_node_info_list[node_n].node);
        m_node_info_list[node_n].node_op_type = compute_op_type(m_node_info_list[node_n].node);
    }
}

namespace {
bool is_inplace_op(const ggml_tensor * node) {
    const bool is_scale_or_fill = node->op == GGML_OP_SCALE || node->op == GGML_OP_FILL;
    return node->op == GGML_OP_SET_ROWS || node->op == GGML_OP_CPY || (is_scale_or_fill && node->view_src);
}

bool is_same_shape(const ggml_tensor * a, const ggml_tensor * b) {
    for (int i = 0; i < GGML_MAX_DIMS; i++) {
        if (a->ne[i] != b->ne[i]) {
            return false;
        }
    }
    return true;
}

bool is_conv_states_all_tensor(const ggml_tensor * tensor) {
    return tensor != nullptr && strncmp(tensor->name, "conv_states_all", strlen("conv_states_all")) == 0;
}

bool is_descending_snapshot_order(const ggml_tensor * order, int64_t capacity, int64_t windows) {
    if (!order || order->op != GGML_OP_VIEW || capacity < 1 || windows < 1 || windows > capacity) {
        return false;
    }
    const auto cast = order->src[0];
    if (!cast || cast->op != GGML_OP_CPY || cast->type != GGML_TYPE_I32 || !cast->src[0] ||
        cast->src[0]->op != GGML_OP_SCALE || !cast->src[0]->src[0] ||
        cast->src[0]->src[0]->op != GGML_OP_ARANGE) {
        return false;
    }
    float scale[2], range[3];
    memcpy(scale, cast->src[0]->op_params, sizeof(scale));
    memcpy(range, cast->src[0]->src[0]->op_params, sizeof(range));
    return cast->ne[0] == capacity && scale[0] == -1 && scale[1] == capacity - 1 &&
           range[0] == 0 && range[1] == capacity && range[2] == 1 &&
           order->ne[0] == windows && ggml_is_contiguous(order) &&
           order->view_offs == size_t(capacity - windows) * sizeof(int32_t);
}
}  // namespace

bool GgmlOvDecoder::is_conv_state_snapshot_writeback(const ggml_tensor * node) {
    if (!node || node->op != GGML_OP_SET_ROWS || !is_recurrent_cache(node->view_src) ||
        !node->src[0] || node->src[0]->op != GGML_OP_VIEW || !node->src[0]->src[0] ||
        node->src[0]->src[0]->op != GGML_OP_CONCAT || !node->src[2] || node->src[2]->op != GGML_OP_VIEW ||
        node->src[2]->view_src != node->view_src) {
        return false;
    }
    const auto source = node->src[0];
    const auto concat = source->src[0];
    const auto dest = node->src[2];
    const auto cache = node->view_src;
    const auto count = dest->ne[1];
    if (!is_descending_snapshot_order(node->src[1], count, source->ne[1])) {
        return false;
    }
    const size_t elem = ggml_type_size(cache->type);
    const size_t row = cache->nb[1];
    const int64_t tokens = concat->ne[0] - source->ne[0];
    return (cache->type == GGML_TYPE_F32 || cache->type == GGML_TYPE_F16) &&
           source->type == cache->type && dest->type == cache->type && ggml_is_contiguous(cache) &&
           cache->ne[2] == 1 && cache->ne[3] == 1 && row > 0 && concat->op_params[0] == 0 &&
           concat->ne[3] == 1 && concat->src[0] && source->ne[0] > 0 && source->ne[2] > 0 && source->ne[3] > 0 &&
           size_t(source->ne[0]) <= row / elem &&
           source->ne[0] == concat->src[0]->ne[0] &&
           source->ne[2] == concat->ne[1] && source->ne[3] == concat->ne[2] &&
           source->nb[0] == elem && source->nb[1] == elem && source->nb[2] == concat->nb[1] &&
           source->nb[3] == concat->nb[2] && source->ne[1] == std::min(tokens, count) &&
           source->view_offs == size_t(tokens - source->ne[1] + 1) * elem &&
           dest->ne[0] == source->ne[0] && dest->ne[2] == source->ne[2] && dest->ne[3] == source->ne[3] &&
           dest->nb[0] == elem && dest->nb[1] > 0 && dest->nb[1] % row == 0 &&
           dest->nb[2] == size_t(source->ne[0]) * elem && dest->nb[3] == row &&
           size_t(source->ne[2]) <= (row - dest->view_offs % row) / dest->nb[2] &&
           size_t(count) <= size_t(cache->ne[1]) / (dest->nb[1] / row) &&
           size_t(dest->ne[3]) <= dest->nb[1] / row &&
           dest->view_offs / row <= dest->nb[1] / row - size_t(dest->ne[3]);
}

// MoE expert aggregation (build_moe_ffn in llama-graph.cpp): each expert plane is
// `ggml_view_2d(experts, n_embd, n_tokens, experts->nb[2], i*experts->nb[1])` and the planes
// are summed with a chain of ADDs: moe_out = ((view_0 + view_1) + view_2) + ... + view_{n-1}.
// Detected structurally by walking the ADD chain and checking every leaf is a same-shape,
// same-stride VIEW of one common base tensor, indexed by a distinct expert-plane offset, and
// that the chain covers every plane of that base (leaf count == base->ne[1]). Only the
// outermost ADD of the chain satisfies this (inner ADDs see fewer leaves than base->ne[1]).
bool is_moe_expert_sum_add(const ggml_tensor * node) {
    std::vector<const ggml_tensor *> leaves;
    const ggml_tensor * cur = node;
    while (cur->op == GGML_OP_ADD) {
        if (cur->src[0] == nullptr || cur->src[1] == nullptr) {
            return false;
        }
        leaves.push_back(cur->src[1]);
        cur = cur->src[0];
    }
    leaves.push_back(cur);

    const ggml_tensor * base = nullptr;
    std::set<int64_t> plane_indices;
    for (const ggml_tensor * leaf : leaves) {
        if (leaf->op != GGML_OP_VIEW || leaf->src[0] == nullptr) {
            return false;
        }
        const ggml_tensor * leaf_base = leaf->src[0];
        if (base == nullptr) {
            base = leaf_base;
        } else if (leaf_base != base) {
            return false;
        }
        if (leaf->ne[0] != base->ne[0] || leaf->ne[1] != base->ne[2] || leaf->ne[2] != 1 || leaf->ne[3] != 1 ||
            leaf->nb[1] != base->nb[2]) {
            return false;
        }
        if (base->nb[1] == 0 || leaf->view_offs % base->nb[1] != 0) {
            return false;
        }
        int64_t plane = static_cast<int64_t>(leaf->view_offs / base->nb[1]);
        if (plane < 0 || plane >= base->ne[1] || !plane_indices.insert(plane).second) {
            return false;
        }
    }

    return base != nullptr && base->ne[1] > 1 && plane_indices.size() == static_cast<size_t>(base->ne[1]);
}

std::string GgmlOvDecoder::get_tensor_name(const ggml_cgraph * cgraph, const ggml_tensor * tensor) {
    if (tensor == nullptr) {
        return "";
    }
    if (tensor->op != GGML_OP_NONE || is_kvcache(tensor, nullptr)) {
        // Hash-table slots depend on tensor addresses and differ between contexts.
        // Graph ordinals disambiguate duplicate names while keeping compiled-model
        // ports identical for equivalent graphs in different contexts, including inactive sampling branches.
        const auto * node = std::find(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, tensor);
        if (node != cgraph->nodes + cgraph->n_nodes) {
            return std::string(tensor->name) + "#n" + std::to_string(node - cgraph->nodes);
        }
        const auto * leaf = std::find(cgraph->leafs, cgraph->leafs + cgraph->n_leafs, tensor);
        if (leaf != cgraph->leafs + cgraph->n_leafs) {
            return std::string(tensor->name) + "#l" + std::to_string(leaf - cgraph->leafs);
        }
        if (cgraph->leafs == nullptr || cgraph->n_leafs == 0) {
            // ggml_graph_view sets n_leafs to 0, loop over all node srcs to give each leaf a unique name
            for (int i = 0; i < cgraph->n_nodes; i++) {
                auto *cur_node = cgraph->nodes[i];
                for (int j = 0; j < GGML_MAX_SRC; j++) {
                    if (cur_node->src[j] == tensor) {
                        return std::string(tensor->name) + "#l" + std::to_string(i * GGML_MAX_SRC + j);
                    }
                }
            }
        }
    }
    return tensor->name;
}

static std::string get_tensor_ov_name(const ggml_cgraph * cgraph, const ggml_tensor * tensor) {
    return GgmlOvDecoder::get_tensor_name(cgraph, tensor);
}

static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder,
                                                  const ggml_cgraph * cgraph,
                                                  const ggml_tensor * tensor,
                                                  const ggml_tensor * op) {
    if (GgmlOvDecoder::is_inp_pos(tensor, op)) {
        return "inp_pos";
    }
    if (GgmlOvDecoder::is_inp_emb(tensor, op)) {
        return "embd";
    }
    // gemma-4's KV-shared layers read the mask rows of their output tokens through GET_ROWS, which is not a mask
    // consumer, so match the masks by identity too
    if (GgmlOvDecoder::is_inp_mask(tensor, op) || decoder->is_kq_mask(tensor)) {
        // Give the two attention masks distinct OV parameter names. build_attn_inp_kq_mask()
        // names the full-attention mask and the sliding-window mask identically, so keying a
        // parameter off the name alone makes the second mask overwrite the first and both
        // attention types read one parameter. Tell them apart by tensor identity, using the
        // SWA classification computed in compute_llm_params(). An empty swa_layers set means
        // there is only one mask in play and the plain name is correct.
        const bool is_swa = decoder->is_swa_mask(tensor);
        if (decoder->is_stateful()) {
            return is_swa ? "self_kq_mask_swa" : "self_kq_mask";
        }
        if (is_swa) {
            return get_tensor_ov_name(cgraph, tensor) + "_swa";
        }
    }
    if (!decoder->get_model_params().swa_layers.empty() && GgmlOvDecoder::is_kv_idx(tensor, op) &&
        op->src[2] != nullptr) {
        // same as the masks: the full and the sliding-window cache get KV write indices of the same name
        const ggml_tensor * cache = op->src[2]->view_src != nullptr ? op->src[2]->view_src : op->src[2];
        auto layer = extract_layer_from_name(cache->name);
        if (layer.has_value() && decoder->is_swa_layer(layer.value())) {
            return get_tensor_ov_name(cgraph, tensor) + "_swa";
        }
    }
    return get_tensor_ov_name(cgraph, tensor);
}

void GgmlOvDecoder::set_input_output() {
    for (int node_n = 0; node_n < m_cgraph->n_nodes; node_n++) {
        auto * node = m_cgraph->nodes[node_n];

        NodeInfo current_node_info;
        auto node_name = get_tensor_ov_name(m_cgraph, node);

        current_node_info.node = node;
        current_node_info.node_name = node_name;
        current_node_info.node_op_case = 0;
        current_node_info.data_addr = node->data;

        for (int i = 0; i < GGML_MAX_SRC; i++) {
            auto * src = node->src[i];
            if (src == nullptr) {
                continue;
            }
            auto src_name = get_tensor_ov_name(m_cgraph, src);
            if (src->flags & GGML_TENSOR_FLAG_INPUT) {
                src_name = get_tensor_graph_input_ov_name(this, m_cgraph, src, node);
            }
            // Same name as in create_weight_nodes(), so ROPE reads the weight Constant.
            if (is_rope_freqs_weight(src->view_src ? src->view_src : src, node)) {
                src_name = "rope_freqs.weight";
            }
            current_node_info.node_inputs[src_name] = src;
            current_node_info.node_inputs_names.push_back(src_name);

            if (src->op == GGML_OP_VIEW) {
                // Traverse upward through nested VIEW operations
                std::remove_reference_t<decltype(current_node_info.node_inputs_views[src_name])> view_chain;
                auto * current = src;

                while (current != nullptr) {
                    auto current_name = get_tensor_ov_name(m_cgraph, current);
                    if (current->flags & GGML_TENSOR_FLAG_INPUT) {
                        current_name = get_tensor_graph_input_ov_name(this, m_cgraph, current, node);
                    }
                    view_chain.emplace_back(current_name, current);
                    // If current src is also a VIEW, continue traversing
                    if (current->src[0] != nullptr && current->src[0]->op == GGML_OP_VIEW) {
                        current = current->src[0];
                    } else {
                        break;
                    }
                }

                // Assign all collected view inputs to node_inputs_views
                current_node_info.node_inputs_views[src_name] = view_chain;
            }
        }

        m_node_info_list.push_back(current_node_info);
    }
}

// True if the GDN attention output is only read by rms_norm (gated norm, e.g. qwen3.5) and the state by
// cache writeback CPYs. Then q may be pre-scaled, since rms_norm cancels the scale. Static (NPU) path only.
bool GgmlOvDecoder::is_gdn_out_prescaled(const ggml_tensor * gdn) const {
    if (!ggml_openvino_is_npu()) {
        return false;
    }
    bool has_norm = false;
    for (int i = 0; i < m_cgraph->n_nodes; i++) {
        const ggml_tensor * n = m_cgraph->nodes[i];
        for (int j = 0; j < GGML_MAX_SRC; j++) {
            const ggml_tensor * s = n->src[j];
            if (s == gdn && n->op != GGML_OP_VIEW) {
                return false;
            }
            if (s == nullptr || s->op != GGML_OP_VIEW || s->src[0] != gdn) {
                continue;
            }
            if (n->op == GGML_OP_RMS_NORM) {
                has_norm = true;
            } else if (n->op != GGML_OP_CPY) {
                return false;
            }
        }
    }
    return has_norm;
}

int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
    int op_case = 0;
    switch (node->op) {
    case GGML_OP_RESHAPE: {
        if (m_naive) {
            break;
        }
        auto name = std::string(node->name);
        auto * src = node->src[0];
        if (src->op == GGML_OP_MUL && node->ne[0] == src->ne[0] * src->ne[1] && node->ne[3] == 1) {
            for (int j = 0; j < 2; ++j) {
                const auto * norm = src->src[j];
                if (norm->op == GGML_OP_MUL) {
                    norm = norm->src[0];
                }
                if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW &&
                    norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
                    // The post-GDN projection rejoins the flat token stream.
                    return node->ne[2] == 1 ? 5 : 6;
                }
            }
        }
        // Identify recurrent sequence reshapes before size checks, which are ambiguous for one token.
        bool recurrent_sequence = false;
        for (int i = 0; i < m_cgraph->n_nodes && !recurrent_sequence; ++i) {
            const auto * consumer = m_cgraph->nodes[i];
            if (consumer->op == GGML_OP_ROPE && consumer->src[1] == node) {
                return 11;
            } else if (consumer->op == GGML_OP_MUL_MAT_ID && consumer->src[1] == node) {
                return 1;
            } else if (consumer->op == GGML_OP_GATED_DELTA_NET) {
                for (int j : {3, 4}) {
                    const auto * gate = consumer->src[j];
                    if (gate->op == GGML_OP_UNARY) {
                        gate = gate->src[0];
                    }
                    if (gate == node) {
                        return 10;
                    }
                }
            } else if (consumer->op == GGML_OP_SSM_CONV) {
                const auto * concat = consumer->src[0];
                if (concat->op == GGML_OP_CONCAT && concat->src[1]->op == GGML_OP_TRANSPOSE) {
                    const auto * seq = concat->src[1]->src[0];
                    // LFM2 short convolutions gate the input first: transpose(mul(view(node), view(node))).
                    if (seq->op == GGML_OP_MUL && seq->src[0]->op == GGML_OP_VIEW && seq->src[0]->src[0] == node &&
                        seq->src[1]->op == GGML_OP_VIEW && seq->src[1]->src[0] == node) {
                        seq = node;
                    }
                    recurrent_sequence = seq == node;
                }
            } else if (consumer->op == GGML_OP_UNARY && ggml_get_unary_op(consumer) == GGML_UNARY_OP_SOFTPLUS) {
                const auto * biased = consumer->src[0];
                recurrent_sequence = biased->op == GGML_OP_ADD && biased->src[0] == node;
            } else if (consumer->op == GGML_OP_MUL) {
                for (int j = 0; j < 2; ++j) {
                    const auto * gate = consumer->src[j];
                    const auto * norm = consumer->src[1 - j];
                    if (gate->op != GGML_OP_UNARY || gate->src[0] != node) {
                        continue;
                    }
                    if (norm->op == GGML_OP_MUL) {
                        norm = norm->src[0];
                    }
                    if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW &&
                        norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
                        return 10;
                    }
                }
            }
        }
        if (recurrent_sequence && node->ne[0] == src->ne[0] && node->ne[3] == 1) {
            return 6;
        }
        if (node->ne[0] == src->ne[0] && node->ne[2] == 1 && node->ne[3] == 1) {
            return 5;
        }
        if (src->op == GGML_OP_RESHAPE && src->src[0]->ne[0] == node->ne[0] && src->src[0]->ne[1] == node->ne[1]) {
            op_case = 4;
        } else if (node->ne[0] == 1 && node->ne[1] == src->ne[0] && ggml_nrows(src) == 1) {
            // [n] -> [1, n] (gemma-4 gathers the positions of its output rows this way): the source dim
            // becomes dim 1. The next check matches too, but would make dim 2 dynamic.
            op_case = 3;
        } else if (node->ne[0] * node->ne[1] == src->ne[0]) {
            op_case = 1;
        } else if (src->ne[0] * src->ne[1] == node->ne[0]) {
            op_case = 2;
            if (src->ne[2] * src->ne[3] == node->ne[1]) {
                op_case = 5;
            }
        } else if (node->ne[0] == 1 && src->ne[0] * src->ne[1] * src->ne[2] == node->ne[1]) {
            op_case = 3;
        } else if (node->ne[0] * node->ne[1] == src->ne[0] * src->ne[1] && node->ne[2] == src->ne[2] &&
                   node->ne[3] == src->ne[3]) {
            // head regroup, e.g. mamba2's [head_dim, n_head, n_tokens, n_seqs] -> [d_inner/n_group, n_group, n_tokens, n_seqs]
            op_case = 1;
        } else if (name.find("linear_attn_qkv_mixed") == 0 || name.find("alpha") == 0) {
            op_case = 6;
        } else if (name.find("linear_attn_out") == 0) {
            op_case = 7;
        } else if (name.find("state_predelta") == 0) {
            op_case = 8;
        }
        const auto it = m_node_dynamic_dims.find(const_cast<ggml_tensor *>(node));
        const int dynamic_dim = it != m_node_dynamic_dims.end() ? it->second : -1;
        // op_case 5 flattens to [x, n_tokens]; a deeper dynamic dim means the size match above held only because
        // there is one token, e.g. the last-layer expert groups with a single output row. op_case 3 ([n] -> [1, n])
        // matches the same way, e.g. the last-layer expert probabilities [n_expert, 1] -> [1, n_expert, 1]
        if (op_case == 1 || op_case == 2 || op_case == 3 || (op_case == 5 && dynamic_dim > 1)) {
            // The rules above read the token dim off a 2D source. With a deeper source, e.g. the MoE expert groups
            // [n_exp_per_group, n_groups, n_tokens], the tracked dynamic dim is the reliable one:
            // op_case 2 marks ggml dim 1, op_case 1 dim 2, op_case 8 dim 3
            if (dynamic_dim == 1) {
                op_case = 2;
            } else if (dynamic_dim == 2) {
                op_case = 1;
            } else if (dynamic_dim == 3) {
                op_case = 8;
            }
        }
        if (op_case == 1 && m_is_stateful) {
            // Recurrent convolution and GDN gates retain their rank-4 layout.
            // The gathered states may come through a view of the one gather of all states (see build_rs).
            const auto * gather = src->op == GGML_OP_VIEW ? src->src[0] : src;
            bool recurrent = gather->op == GGML_OP_GET_ROWS && is_recurrent_cache(gather->src[0]);
            for (int i = 0; i < m_cgraph->n_nodes && !recurrent; ++i) {
                const auto * consumer = m_cgraph->nodes[i];
                if (consumer->op == GGML_OP_GATED_DELTA_NET) {
                    for (int j : {3, 4}) {
                        const auto * gate = consumer->src[j];
                        if (gate->op == GGML_OP_UNARY) {
                            gate = gate->src[0];
                        }
                        recurrent = recurrent || gate == node;
                    }
                } else if (consumer->op == GGML_OP_MUL) {
                    for (int j = 0; j < 2; ++j) {
                        const auto * gate = consumer->src[j];
                        const auto * norm = consumer->src[1 - j];
                        if (gate->op != GGML_OP_UNARY || gate->src[0] != node) {
                            continue;
                        }
                        if (norm->op == GGML_OP_MUL) {
                            norm = norm->src[0];
                        }
                        recurrent = recurrent || (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW &&
                                                   norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET);
                    }
                }
            }
            if (recurrent) {
                op_case = 9;
            }
        }
        break;
    }
    case GGML_OP_PERMUTE: {
        if (node->src[0]->op != GGML_OP_VIEW) {
            op_case = 1;
        } else if (node->src[0]->src[0]->op == GGML_OP_NONE) {
            // kv cache tensor
            std::string src_name(node->view_src->name);
            int layer = extract_layer_from_name(src_name).value();
            // a transposed V cache view is contiguous too when the attended length is the whole cache (one ubatch
            // that fills it)
            const bool v_trans_cache = m_model_params.v_trans && src_name.rfind("cache_v_l", 0) == 0;
            if (ggml_is_contiguous(node->src[0]) && !v_trans_cache) {
                // -  19: [    64,     8,   256,     1] VIEW            cache_k_l0 (view)             [ 2,   128,  1024, 1048576]
                //         [   512,  1024,     1,     1]      0: NONE     cache_k_l0                    [ 2,  1024, 1048576, 1048576]
                // -  20: [    64,   256,     8,     1] PERMUTE         cache_k_l0 (view) (permuted)  [ 2,  1024,   128, 1048576]
                //         [    64,     8,   256,     1]      0: VIEW     cache_k_l0 (view)             [ 2,   128,  1024, 1048576]
                if (!is_swa_layer(layer)) {
                    op_case = 3;
                } else {
                    op_case = 4;
                }
            } else {
                // special case of cache v when `-fa off`
                // -  17: [   256,     8,    64,     1] VIEW            cache_v_l0 (view)             [ 2, 131072,  2048, 1048576]
                //         [   512,  1024,     1,     1]      0: NONE     cache_v_l0                   [ 2,  1024, 1048576, 1048576]
                // -  18: [   256,    64,     8,     1] PERMUTE         cache_v_l0 (view) (permuted)  [ 2,  2048, 131072, 1048576]
                //         [   256,     8,    64,     1]      0: VIEW     cache_v_l0 (view)            [ 2, 131072,  2048, 1048576]
                if (!is_swa_layer(layer)) {
                    op_case = 5;
                } else {
                    op_case = 6;
                }
            }
        } else {
            // rope'ed query tensor
            op_case = 2;
        }
        break;
    }
    case GGML_OP_SET_ROWS: {
        if (is_conv_state_snapshot_writeback(node)) {
            op_case = 3;
            break;
        }
        if (is_column_set_rows(node)) {
            op_case = 4;
            break;
        }
        // `-fa off` writes the V cache transposed, through a [1, n] reshape of the cache: one element per row
        if (node->src[2] != nullptr && node->src[2]->op == GGML_OP_RESHAPE && node->src[2]->ne[0] == 1 &&
            is_kvcache(node->src[2]->src[0], nullptr)) {
            op_case = 1;
        } else if (!is_kvcache_write(node)) {
            op_case = 2;
        }
        break;
    }
    case GGML_OP_MUL_MAT: {
        if (node->src[1]->op == GGML_OP_SOFT_MAX) {
            // In the case of `-fa off`, softmax is used, v_trans=true, the dynamic dim is ne[0] for cache_v
            op_case = 2;
        }
        break;
    }
    case GGML_OP_GET_ROWS: {
        // GET_ROWS gathering recurrent state cache rows via the inp->s_copy index list:
        // src[0] is a reshape of cache_r/cache_s, src[1] is a view of the s_copy leaf, or the leaf itself
        // when one gather covers all states (see build_rs).
        // op_case 1/2: active/extra rows, independent of cache capacity.
        if (node->src[0]->op == GGML_OP_RESHAPE && node->src[0]->src[0] != nullptr &&
            is_recurrent_cache(node->src[0]->src[0])) {
            if (node->src[1]->op == GGML_OP_VIEW) {
                op_case = node->src[1]->view_offs == 0 ? 1 : 2;
            }
        } else if (is_get_rows_batched_4d(node)) {
            // with one token the batch dims look like a 3D gather; the tracked token dim tells them apart
            const auto it = m_node_dynamic_dims.find(const_cast<ggml_tensor *>(node));
            if (node->ne[3] > 1 || (it != m_node_dynamic_dims.end() && it->second == 3)) {
                op_case = 5;
            }
        }
        break;
    }
    case GGML_OP_ROPE: {
        const int mode = node->op_params[2];
        switch (mode) {
        case GGML_ROPE_TYPE_NEOX: {
            op_case = 1;
            break;
        }
        case GGML_ROPE_TYPE_IMROPE: {
            op_case = 2;
            break;
        }
        case GGML_ROPE_TYPE_VISION: {
            op_case = 3;
            break;
        }
        case GGML_ROPE_TYPE_MROPE: {
            op_case = 4;
            break;
        }
        default:
            op_case = 0;
            break;
        }
        break;
    }
    case GGML_OP_VIEW: {
        if (is_sampling_view(node)) {
            return 3;
        }
        if (node->view_offs == 0 && node->src[0]->op == GGML_OP_GET_ROWS &&
            is_recurrent_cache(node->src[0]->src[0]) && node->ne[0] == node->src[0]->ne[0] &&
            node->ne[2] == 1 && node->ne[3] == 1 && m_compute_params.s_copy_active_slot_len != -1) {
            // build_rs gathers active and inactive rows together; consumers need only the
            // active prefix, whose length changes independently of the gather's row count.
            return 4;
        }
        if (is_direct_gdn_view(node)) {
            // The GDN translator publishes native attention/state outputs under these VIEW names.
            op_case = 2;
            break;
        }
        if (m_is_static && node->src[0] != nullptr &&
            (node->src[0]->op == GGML_OP_GATED_DELTA_NET || node->src[0]->op == GGML_OP_CONCAT)) {
            // VIEW slicing a GATED_DELTA_NET combined [attn|state] output, or the conv_input
            // CONCAT. The consuming CPY/RMS_NORM op recovers the true window at runtime via
            // ssm_state_size / the fixed conv kernel width, so this VIEW must stay an identity
            // pass-through of the full source here too (it already is on the dynamic path);
            // otherwise the generic static-mode Slice below would bake in the *captured*
            // cgraph's token count, which is wrong once the compiled static model runs with a
            // different token count (prefill chunk size or 1).
            op_case = 1;
            break;
        }
        break;
    }
    case GGML_OP_RMS_NORM: {
        if (node->src[0]->op == GGML_OP_VIEW) {
            if (is_same_shape(node->src[0]->src[0], node->src[0])) {
                op_case = 1;
            } else if (is_direct_gdn_view(node->src[0])) {
                // GDN attention is routed directly to this VIEW by get_output_names(). 3: the GDN q input may be
                // pre-scaled, and the norm then scales its eps to match; 4: it is not.
                op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 4;
            } else if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
                // packed [attn | state] output, sliced by the norm. 5: pre-scaled, as in 3; 2: not.
                op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 5 : 2;
            }
        }
        break;
    }
    case GGML_OP_GATED_DELTA_NET: {
        if (is_gdn_out_prescaled(node)) {
            op_case = 1;
        }
        break;
    }
    case GGML_OP_POOL_1D:
    case GGML_OP_POOL_2D: {
        const ggml_op_pool pool_mode = static_cast<ggml_op_pool>(node->op_params[0]);
        switch (pool_mode) {
        case GGML_OP_POOL_MAX: {
            op_case = 1;
            break;
        }
        case GGML_OP_POOL_AVG: {
            op_case = 2;
            break;
        }
        default:
            op_case = 0;
            break;
        }
        break;
    }
    case GGML_OP_UPSCALE: {
        const int32_t mode_flags = node->op_params[0];
        const ggml_scale_mode scale_mode = static_cast<ggml_scale_mode>(mode_flags & 0xFF);
        switch (scale_mode) {
        case GGML_SCALE_MODE_NEAREST: {
            op_case = 1;
            break;
        }
        case GGML_SCALE_MODE_BILINEAR: {
            op_case = 2;
            break;
        }
        case GGML_SCALE_MODE_BICUBIC: {
            op_case = 3;
            break;
        }
        default:
            op_case = 0;
            break;
        }
        break;
    }
    case GGML_OP_CPY: {
        if (node->src[0]->op == GGML_OP_VIEW) {
            if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
                if (is_gdn_snapshot_writeback(node)) {
                    op_case = is_direct_gdn_view(node->src[0]) ? 12 : 11;
                } else if (!m_model_params.has_rs_rollback) {
                    // Write native GDN state into the runtime active range of the cache.
                    op_case = 10;
                } else {
                    op_case = 1;
                }
            } else if (is_ssm_state_writeback(node)) {
                op_case = 13;
                break;
            } else if (GgmlOvDecoder::is_conv_state_writeback(node)) {
                op_case = 2;
                break;
            } else if (is_conv_states_all_tensor(node->view_src) && node->src[1] != nullptr &&
                       node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src) {
                op_case = 4;
                break;
            } else if (node->src[0]->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr &&
                       node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr &&
                       is_recurrent_cache(node->src[1]->view_src)) {
                // Remainder view of the combined state gather (see build_rs).
                op_case = 3;
            }
        } else if (node->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr &&
                   node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr &&
                   is_recurrent_cache(node->src[1]->view_src)) {
            // s_copy defrag remainder writeback: gathered extra state rows copied back into the cache
            op_case = 3;
        } else if (node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr) {
            // op_case 5: KV write for decoder self-attention (dynamic write offset)
            // op_case 6: KV write for encoder self-attn or cross-attn (static offset)
            const ggml_tensor * kv_buf = node->src[1]->view_src;
            if (kv_buf->ne[1] == 1 && kv_buf->ne[2] == 1 && kv_buf->ne[3] == 1) {
                op_case = 6;
                // Forward-scan the graph for a FLASH_ATTN_EXT that reads from
                // the same buffer. Having a mask (src[3] != nullptr) implies
                // decoder self-attention and the write offset is dynamic.
                for (int i = 0; i < m_cgraph->n_nodes; i++) {
                    const ggml_tensor * n = m_cgraph->nodes[i];
                    if (n->op != GGML_OP_FLASH_ATTN_EXT) {
                        continue;
                    }
                    // K (src[1]) and V (src[2]) are 3-D views whose view_src is
                    // the flat KV buffer we are writing to.
                    if ((n->src[1] != nullptr && n->src[1]->view_src == kv_buf) ||
                        (n->src[2] != nullptr && n->src[2]->view_src == kv_buf)) {
                        if (n->src[3] != nullptr) {
                            op_case = 5;  // decoder self-attention: mask present
                        }
                        break;
                    }
                }
            }
        }
        break;
    }
    case GGML_OP_ADD: {
        if (is_moe_expert_sum_add(node)) {
            // Outermost ADD of a MoE expert-plane sum chain: translated as a single
            // ReduceSum over the base tensor instead of N-1 chained Adds over N Slices.
            op_case = 1;
        }
        break;
    }
    case GGML_OP_SCALE:
    case GGML_OP_FILL: {
        if (node->view_src && node->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY) {
            op_case = 1;
        }
        break;
    }
    case GGML_OP_L2_NORM: {
        if (std::string(node->name).find("predelta") != std::string::npos) {
            op_case = 1;
        }
        break;
    }
    case GGML_OP_FLASH_ATTN_EXT: {
        if (node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr) {
            const ggml_tensor * kv_buf = node->src[1]->view_src;
            if (kv_buf->ne[1] == 1 && kv_buf->ne[2] == 1 && kv_buf->ne[3] == 1) {
                op_case = (node->src[3] != nullptr) ? 1 : 2;
            }
        }
        break;
    }
    default:
        break;
    }
    return op_case;
}

std::optional<int> extract_layer_from_name(const std::string & name) {
    size_t pos1 = name.find("_l");
    if (pos1 == std::string::npos) {
        return std::nullopt;
    }
    pos1 += 2;
    if (pos1 >= name.size() || !std::isdigit(static_cast<unsigned char>(name[pos1]))) {
        return std::nullopt;
    }
    return std::stoi(name.substr(pos1));
}

// Recover the sliding window width from ggml's own SWA mask. llama.cpp never passes n_swa to a
// backend, but fill_mask() writes it into the mask: a query row keeps exactly the cells inside
// its window, so the widest row counts min(pos + 1, n_swa) unmasked cells. Counting rather than
// looking for a contiguous band is what makes this work on the KV-cache mask, where columns are
// physical cache cells in arbitrary order, not positions.
// Assumes LLAMA_SWA_TYPE_STANDARD, the only type the caller reconstructs.
static int get_swa_window_from_mask(const ggml_tensor * mask) {
    if (mask->data == nullptr || !ggml_backend_buffer_is_host(mask->buffer)) {
        return -1;
    }
    if (mask->type != GGML_TYPE_F16 && mask->type != GGML_TYPE_F32) {
        return -1;
    }

    const int64_t n_kv = mask->ne[0];
    const int64_t n_tokens = mask->ne[1];
    int64_t window = 0;

    for (int64_t r = 0; r < n_tokens; r++) {
        int64_t kept = 0;
        for (int64_t c = 0; c < n_kv; c++) {
            const size_t i = (size_t) r * n_kv + c;
            const float v = mask->type == GGML_TYPE_F16 ? ggml_fp16_to_fp32(((const ggml_fp16_t *) mask->data)[i]) :
                                                          ((const float *) mask->data)[i];
            if (v > -INFINITY) {
                kept++;
            }
        }
        window = std::max(window, kept);
    }

    return window > 0 ? (int) window : -1;
}

// The KQ product that the SOFT_MAX of an attention reads: directly, or through the logit soft-capping of gemma-2
// (SCALE, TANH, SCALE)
static const ggml_tensor * softmax_scores_source(const ggml_tensor * scores) {
    while (scores != nullptr && (scores->op == GGML_OP_SCALE ||
                                 (scores->op == GGML_OP_UNARY && ggml_get_unary_op(scores) == GGML_UNARY_OP_TANH))) {
        scores = scores->src[0];
    }
    return scores;
}

std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgraph * cgraph, bool is_static) {
    ModelParams model_params;
    ComputeParams compute_params;
    auto get_attention_pattern_case = [](const ggml_tensor * node) -> int {
        if (node == nullptr) {
            return -1;
        }

        switch (node->op) {
        case GGML_OP_FLASH_ATTN_EXT:
            if (node->src[0] == nullptr || node->src[1] == nullptr) {
                return -1;
            }
            switch (node->src[1]->op) {
            case GGML_OP_PERMUTE:
                // case 0: src[1] is PERMUTE of a cache VIEW, mask required
                if (node->src[3] != nullptr && node->src[1]->src[0] != nullptr &&
                    node->src[1]->src[0]->op == GGML_OP_VIEW) {
                    return 0;
                }
                break;
            case GGML_OP_CPY:
                // case 1: src[1] is CPY of a PERMUTE(VIEW), mask required
                if (node->src[3] != nullptr && node->src[1]->src[0] != nullptr &&
                    node->src[1]->src[0]->op == GGML_OP_PERMUTE && node->src[1]->src[0]->src[0] != nullptr &&
                    node->src[1]->src[0]->src[0]->op == GGML_OP_VIEW) {
                    return 1;
                }
                break;
            case GGML_OP_VIEW:
                // cases 4/5/6: whisper - K is a direct non-contiguous VIEW_3D of a KV cache
                if (node->src[1]->view_src != nullptr) {
                    if (node->src[3] != nullptr) {
                        return 4;  // decoder self-attention
                    }
                    return 5;      // cross-attention or encoder self-attention
                }
                break;
            default:
                break;
            }
            break;
        case GGML_OP_SOFT_MAX: {
            // case 2: node op is SOFT_MAX, its scores come from a MUL_MAT (see softmax_scores_source) & the src 0 of MUL_MAT is PERMUTE & the permuted tensor src is the view of cache k
            const ggml_tensor * kq = softmax_scores_source(node->src[0]);
            if (kq != nullptr && node->src[1] != nullptr && kq->op == GGML_OP_MUL_MAT && kq->src[0] != nullptr &&
                kq->src[1] != nullptr && kq->src[0]->op == GGML_OP_PERMUTE && kq->src[0]->src[0] != nullptr &&
                kq->src[0]->src[0]->op == GGML_OP_VIEW) {
                return 2;
            }
            // case 3: node op is SOFT_MAX, src 0 not null & op is ADD & the src 0 of ADD is MUL_MAT & the src 0 of MUL_MAT is PERMUTE
            if (node->src[0]->op == GGML_OP_ADD && node->src[0]->src[0] != nullptr &&
                node->src[0]->src[0]->op == GGML_OP_MUL_MAT && node->src[0]->src[0]->src[0] != nullptr &&
                node->src[0]->src[0]->src[0]->op == GGML_OP_PERMUTE) {
                return 3;
            }
            break;
        }
        default:
            break;
        }

        return -1;
    };

    // Resolve the attention mask an attention node consumes, mirroring the src layout that
    // get_attention_pattern_case() classifies. Used by the SWA pre-pass below.
    auto get_attention_op_mask = [&get_attention_pattern_case](const ggml_tensor * node) -> const ggml_tensor * {
        switch (get_attention_pattern_case(node)) {
        case 0:
        case 1:
            return node->src[3];
        case 2:
        case 3:
            return node->src[1];
        default:
            return nullptr;
        }
    };

    // The PERMUTE of the K cache view an attention node reads, for the same src layouts
    auto get_attention_cache_k_permute = [&get_attention_pattern_case](const ggml_tensor * node) -> ggml_tensor * {
        switch (get_attention_pattern_case(node)) {
        case 0:
            return node->src[1];
        case 1:
            return node->src[1]->src[0];
        case 2:
            return softmax_scores_source(node->src[0])->src[0];
        case 3:
            return node->src[0]->src[0]->src[0];
        default:
            return nullptr;
        }
    };

    // Pre-pass: classify sliding-window vs full-attention layers.
    //
    // An interleaved-SWA model keeps two KV caches and two attention masks, and hands each layer
    // whichever pair matches its attention type. The mask tensor does not say which is which: both
    // are named "attn_inp_kq_mask" by build_attn_inp_kq_mask(), and both carry the same n_kv because
    // llama_kv_cache::get_n_kv() pads occupancy up to a common multiple.
    //
    // The KV cache does say. Each cache allocates cache_k_l<N> once at load time with its own cell
    // count: the windowed cache is sized from the window
    // (PAD(min(size_base, n_swa*(unified ? n_seq_max : 1) + n_ubatch), 256), see
    // llama_kv_cache_iswa), the full-attention one spans the whole context. Read the LEAF buffer
    // behind the VIEW rather than the VIEW itself: the leaf extent is a constant per layer, known
    // from the first graph onwards, while the view grows with context depth and would invert the
    // comparison at shallow depth.
    //
    // Layers whose leaf is smaller than the largest leaf are the windowed ones. Equal extents do not
    // rule them out: the windowed cache is padded to n_swa + n_ubatch, which can equal the full
    // context (gemma-4 at -c 1024 -ub 512). See the mask fallback below.
    //
    // Getting this wrong is silent and severe: with the windowed layers classified as
    // full-attention, permute's KV slicing uses attention_size instead of attention_size_swa. The
    // two agree while the context is shorter than the window, then diverge, and the mask add fails
    // shape inference ("Failed to broadcast-merge input shapes") partway into a long prompt.
    {
        std::map<int, int64_t> layer_extent;                      // layer -> leaf cache_k cell count
        std::map<int, const ggml_tensor *> layer_mask;            // layer -> mask it consumes
        int64_t max_extent = 0;

        for (int i = 0; i < cgraph->n_nodes; i++) {
            const ggml_tensor * mask = get_attention_op_mask(cgraph->nodes[i]);
            if (mask == nullptr) {
                continue;
            }
            const ggml_tensor * cache_k_view = get_attention_cache_k_permute(cgraph->nodes[i])->src[0];
            if (cache_k_view->op != GGML_OP_VIEW) {
                continue;
            }
            const ggml_tensor * leaf = cache_k_view->src[0];
            auto layer = extract_layer_from_name(leaf->name);
            if (!layer.has_value()) {
                continue;
            }
            layer_extent[layer.value()] = leaf->ne[1];
            // the layer's own attention comes first: gemma-4's KV-shared layers read the same cache with mask rows
            // taken from the graph input
            layer_mask.emplace(layer.value(), mask);
            max_extent = std::max(max_extent, leaf->ne[1]);
            if (mask->op == GGML_OP_NONE) {
                model_params.kq_masks.insert(mask);
            }
        }

        for (const auto & [layer, extent] : layer_extent) {
            if (extent < max_extent) {
                model_params.swa_layers.push_back(layer);
                if (model_params.swa_mask == nullptr) {
                    model_params.swa_mask = layer_mask[layer];
                }
            }
        }

        // equal extents: tell the two masks apart by the layers that read them, the larger group gets the swa role
        // (gemma-4: 4 of 5 layers). Groups of equal size can not be told apart, so leave the layers unclassified.
        // Two masks do not imply swa (deepseek sparse attention builds two full masks), but the role does not need
        // them to: it gives each group its own mask, KV write indices and attention size, which is right either way.
        // The only use of the window itself, the stateful mask rebuild, reads it back from the mask, and on a full
        // mask that gives back the causal mask. Decide from the first graph, before the window shows in the mask, so
        // the graph does not change, and is not recompiled, when it does.
        // TODO: "larger group is swa" is a model-level guess. Revisit when llama.cpp tells the backend which layers
        // use a sliding window. Stateless graphs only need the two groups kept apart (separate mask, KV write index
        // and attention size inputs), not the swa role itself, so the guess could be limited to stateful execution.
        if (model_params.swa_layers.empty()) {
            std::map<const ggml_tensor *, std::vector<int>> mask_layers;
            for (const auto & [layer, mask] : layer_mask) {
                mask_layers[mask].push_back(layer);
            }
            if (mask_layers.size() == 2 &&
                mask_layers.begin()->second.size() != std::next(mask_layers.begin())->second.size()) {
                auto swa = mask_layers.begin();
                if (std::next(swa)->second.size() > swa->second.size()) {
                    swa = std::next(swa);
                }
                model_params.swa_layers = swa->second;
                model_params.swa_mask = swa->first;
            }
        }
        std::sort(model_params.swa_layers.begin(), model_params.swa_layers.end());

        if (ggml_openvino_getenv_int("GGML_OPENVINO_LOG_SWA_LAYERS")) {
            std::string per_layer;
            for (const auto & [layer, extent] : layer_extent) {
                per_layer += " " + std::to_string(layer) + ":" + std::to_string(extent) +
                             (extent < max_extent ? "(swa)" : "");
            }
            GGML_LOG_WARN("ov-swa: attn_layers=%zu max_extent=%ld swa_layers=%zu |%s\n", layer_extent.size(),
                          (long) max_extent, model_params.swa_layers.size(), per_layer.c_str());
        }
    }

    bool rope_seen = false;
    for (int i = 0; i < cgraph->n_nodes; i++) {
        ggml_tensor * node = cgraph->nodes[i];
        // `-fa off` stores the V cache transposed: SET_ROWS writes it through a [1, n] reshape, one element per row
        if (node->op == GGML_OP_SET_ROWS && node->src[2] != nullptr && node->src[2]->op == GGML_OP_RESHAPE &&
            node->src[2]->ne[0] == 1 && is_kvcache(node->src[2]->src[0], nullptr)) {
            model_params.v_trans = true;
        }
        if (node->op == GGML_OP_FLASH_ATTN_EXT) {
            float logit_softcap = 0.0f;
            memcpy(&logit_softcap, (const float *) node->op_params + 2, sizeof(float));
            model_params.softcap_attn = model_params.softcap_attn || logit_softcap != 0.0f;
        }
        const int attention_pattern_case = get_attention_pattern_case(node);
        if (attention_pattern_case != -1) {
            ggml_tensor * cache_k_permute = get_attention_cache_k_permute(node);
            ggml_tensor * mask = nullptr;

            switch (attention_pattern_case) {
            case 0:
            case 1:
                mask = node->src[3];
                break;
            case 2:
            case 3:
                mask = node->src[1];
                break;
            case 4:
            case 5: {
                // whisper: K is a direct VIEW_3D of the KV buffer, no PERMUTE node
                auto * cache_k_view = node->src[1];  // VIEW_3D of kv_self.k or kv_cross.k`
                compute_params.token_len_per_seq = node->src[0]->ne[1];
                if (attention_pattern_case == 4) {
                    compute_params.attention_size = cache_k_view->ne[1];
                } else {
                    compute_params.attention_size_static = cache_k_view->ne[1];
                }
                continue;
            }
            default:
                break;
            }

            assert(cache_k_permute != nullptr);

            model_params.head_size = cache_k_permute->ne[0];
            model_params.n_heads_kv = cache_k_permute->ne[2];
            // gemma-4's KV-shared layers attend for the output tokens only, so the batch is the largest query
            compute_params.input_len = std::max<int>(compute_params.input_len, node->src[0]->ne[1]);
            compute_params.token_len_per_seq = std::max<int>(compute_params.token_len_per_seq, node->src[0]->ne[1]);

            auto * cache_k_view = cache_k_permute->src[0];
            if (cache_k_view->op != GGML_OP_VIEW || mask == nullptr) {
                continue;
            }

            ggml_tensor * cache_k = cache_k_view->src[0];
            const auto layer_opt = extract_layer_from_name(cache_k->name);
            if (!layer_opt) {
                continue;
            }
            const int layer = *layer_opt;

            // Classified by the pre-pass above, which groups layers by mask tensor identity. The
            // mask NAME cannot be used: build_attn_inp_kq_mask() gives both masks the same name.
            const bool layer_is_swa = std::find(model_params.swa_layers.begin(), model_params.swa_layers.end(),
                                                layer) != model_params.swa_layers.end();

            model_params.kv_buffer_ctx_id = ggml_backend_openvino_buffer_get_ctx_id(cache_k->buffer);
            model_params.n_heads_kv_per_layer[layer] = cache_k_permute->ne[2];
            if (layer_is_swa) {
                model_params.ctx_per_seq_swa = cache_k->ne[1];
            } else {
                model_params.ctx_per_seq = cache_k->ne[1];
                model_params.n_seq = cache_k->ne[2];
            }

            compute_params.n_seq_active = mask->ne[3];
            auto seq_size = cache_k->ne[0] * cache_k->ne[1] * ggml_type_size(cache_k->type);
            size_t offset;
            memcpy(&offset, cache_k_view->op_params, sizeof(size_t));
            compute_params.seq_active_start = offset / seq_size;

            // a mask that is itself a graph input has the shape of its OV parameter
            const std::string mask_name = mask->op != GGML_OP_NONE      ? std::string() :
                                          mask == model_params.swa_mask ? get_tensor_ov_name(cgraph, mask) + "_swa" :
                                                                          get_tensor_ov_name(cgraph, mask);
            // gemma-4's KV-shared layers come last and take their mask rows from the input masks with GET_ROWS: keep
            // the name and window read from the input
            const bool derived_mask = mask_name.empty();
            if (layer_is_swa) {
                compute_params.attention_size_swa = mask->ne[0];
                if (!derived_mask || compute_params.mask_swa_name.empty()) {
                    compute_params.swa_window = get_swa_window_from_mask(mask);
                    compute_params.mask_swa_name = mask_name;
                }
            } else {
                compute_params.attention_size = mask->ne[0];
                if (!derived_mask || compute_params.mask_name.empty()) {
                    compute_params.mask_name = mask_name;
                }
            }
            if (is_static) {
                const bool slice_prefill = ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1;
                if (!slice_prefill) {
                    compute_params.attention_size = model_params.ctx_per_seq;
                }
                compute_params.attention_size_swa = model_params.ctx_per_seq_swa;
                compute_params.token_len_per_seq = 1;
            }
        }

        if (node->op == GGML_OP_MUL_MAT && node->src[0]->op == GGML_OP_PERMUTE &&
            node->src[0]->src[0]->op == GGML_OP_VIEW && is_kvcache(node->src[0]->view_src, node->view_src)) {
            if (node->src[1]->op == GGML_OP_PERMUTE && node->src[1]->src[0]->op == GGML_OP_VIEW &&
                node->src[1]->src[0]->src[0]->op == GGML_OP_ROPE) {
                compute_params.attention_size = node->ne[0];
                compute_params.mask_name.clear();
            }
        }

        // if the node op is TRANSPOSE and its input is PERMUTE and the source of the PERMUTE is VIEW, then get the attention size with the TRANSPOSE node ne[0] (in case no GGML_OP_FLASH_ATTN_EXT)
        if (node->op == GGML_OP_TRANSPOSE && node->src[0]->op == GGML_OP_PERMUTE &&
            node->src[0]->src[0]->op == GGML_OP_VIEW) {
            compute_params.attention_size = node->ne[0];
            compute_params.mask_name.clear();
            if (is_static && !(ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1)) {
                compute_params.attention_size = model_params.ctx_per_seq;
            }
        }
        if (node->op == GGML_OP_ROPE) {
            if (compute_params.token_len_per_seq == -1 && node->src[1] != nullptr) {
                compute_params.token_len_per_seq = ggml_nelements(node->src[1]);
            }

            // When multiple ROPE ops in the graph disagree on op_params (e.g. gemma4's
            // mixed SWA/non-SWA layers with different n_dims or freq_base), we cannot
            // share a single precomputed rope_sin/rope_cos. Track divergence so the
            // translator falls back to per-op make_sin_cos in that case.
            static_assert(sizeof(model_params.rope_params) == sizeof(int32_t) * 16, "rope_params size");
            if (!rope_seen) {
                memcpy(model_params.rope_params, node->op_params, sizeof(int32_t) * 16);
                rope_seen = true;
            } else if (memcmp(model_params.rope_params, node->op_params, sizeof(int32_t) * 16) != 0) {
                model_params.mixed_rope_params = true;
            }
        }
        if (node->op == GGML_OP_GATED_DELTA_NET) {
            model_params.state_size = node->src[0]->ne[0];
            model_params.has_rs_rollback |= node->op_params[0] > 1;
            compute_params.gdn_attention_rows[get_tensor_ov_name(cgraph, node)] = node->src[2]->ne[2] * node->src[2]->ne[3];
        }
        if (is_sampling_view(node)) {
            compute_params.sampling_rows[get_tensor_ov_name(cgraph, node)] =
                (node->flags & GGML_TENSOR_FLAG_COMPUTE) ? node->view_offs / node->src[0]->nb[1] : 0;
        }
        if (is_gdn_snapshot_writeback(node)) {
            const auto * source = node->src[0];
            const auto * destination = node->src[1];
            const auto * packed = source->src[0];
            ComputeParams::RsWriteback writeback;
            writeback.slot_begin = destination->view_offs / destination->nb[1];
            writeback.src_begin = source->view_offs / packed->nb[1];
            writeback.seq_count = destination->ne[1];
            writeback.snapshot_stride = destination->nb[2] / destination->nb[1];
            compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
        }
        if (is_ssm_state_writeback(node)) {
            ComputeParams::RsWriteback writeback;
            writeback.slot_begin = (int64_t) (node->src[1]->view_offs / node->src[1]->nb[1]);
            compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
        }
        if (is_conv_state_snapshot_writeback(node)) {
            const auto source = node->src[0];
            const auto dest = node->src[2];
            ComputeParams::RsWriteback writeback;
            writeback.slot_begin = dest->view_offs / node->view_src->nb[1];
            writeback.src_begin = source->view_offs / source->nb[0];
            writeback.seq_count = dest->ne[3];
            writeback.snapshot_stride = dest->nb[1] / node->view_src->nb[1];
            writeback.window_count = source->ne[1];
            compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
            compute_params.s_copy_active_slot_len = dest->ne[3];
        }
        if (is_recurrent_cache_reset(node)) {
            if (model_params.n_rs_slots == -1) {
                model_params.n_rs_slots = node->view_src->ne[1];
            } else {
                GGML_ASSERT(model_params.n_rs_slots == node->view_src->ne[1]);
            }
            compute_params.cache_rs_reset_len = ggml_nelements(node) / node->view_src->ne[0];
            compute_params.cache_rs_reset_idx = node->src[0]->view_offs / node->view_src->nb[1];
        }
        // Capture the destination slot block of every recurrent state cache writeback, plus the
        // source window needed by conv state and packed GDN rollback writes. The active sequences
        // occupy a contiguous slot block [begin, begin + n_seqs) of the cache; these offsets move
        // with the batch, so they are fed to the cached model as runtime inputs.
        if (node->op == GGML_OP_CPY && node->view_src != nullptr && is_recurrent_cache(node->view_src) &&
            node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src) {
            const bool is_conv = is_conv_state_writeback(node);
            const bool is_gdn = node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr &&
                                node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET;
            const bool is_extra_view = node->src[0]->op == GGML_OP_VIEW &&
                                       node->src[0]->src[0]->op == GGML_OP_GET_ROWS;
            const bool is_extra = node->src[0]->op == GGML_OP_GET_ROWS || is_extra_view;
            const bool is_gdn_rollback = is_gdn && is_same_shape(node->src[0], node->src[1]);

            const ggml_tensor * dest_view = node->src[1];
            const ggml_tensor * cache = node->view_src;
            const size_t row_bytes = cache->ne[0] * ggml_type_size(cache->type);
            if (is_gdn_rollback) {
                // Rollback GDN exposes an already-flattened [state, seq, snapshot] VIEW and copies
                // it to an identically-shaped cache VIEW. Non-rollback copies native 4-D state
                // [value, key, head, seq] into flattened cache rows, so the shapes differ. This
                // signature is local to the CPY and still works when fallback splits the graph.
                model_params.has_rs_rollback = true;
            }
            if (row_bytes > 0 && (is_conv || is_gdn || is_extra) &&
                !(is_gdn && node->src[0]->src[0]->op_params[0] > 1)) {
                ComputeParams::RsWriteback writeback;
                writeback.slot_begin = (int) (dest_view->view_offs / row_bytes);
                if (is_conv) {
                    writeback.src_begin = (int) (node->src[0]->view_offs / node->src[0]->view_src->nb[0]);
                } else if (is_gdn_rollback) {
                    writeback.src_begin = (int) (node->src[0]->view_offs / node->src[0]->view_src->nb[1]);
                } else if (is_extra_view) {
                    writeback.src_begin = (int) (node->src[0]->view_offs / row_bytes);
                }
                compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
            }
            if (is_conv || is_gdn) {
                // One cache row per active sequence: [conv_state_size, n_seqs] (qwen35) or, with the q/k/v conv
                // states packed in one row, [d_conv - 1, d_inner, n_seqs] (bailingmoe3), so count the rows spanned.
                compute_params.s_copy_active_slot_len = (int) ((ggml_nbytes(dest_view) + row_bytes - 1) / row_bytes);
            }
        }
    }
    if (model_params.n_heads_kv == -1) {
        for (int i = 0; i < cgraph->n_nodes; i++) {
            const auto * node = cgraph->nodes[i];
            const ggml_tensor * mask = nullptr;
            if (node->op == GGML_OP_SOFT_MAX) {
                mask = node->src[1];
            } else if (node->op == GGML_OP_FLASH_ATTN_EXT) {
                mask = node->src[3];
            } else {
                continue;
            }
            if (mask == nullptr || mask->op != GGML_OP_NONE || !(mask->flags & GGML_TENSOR_FLAG_INPUT) ||
                node->src[0] == nullptr) {
                continue;
            }
            model_params.is_cacheless_attn = true;
            model_params.n_seq = 1;
            model_params.ctx_per_seq = mask->ne[0];
            compute_params.input_len = node->src[0]->ne[1];
            compute_params.token_len_per_seq = compute_params.input_len;
            break;
        }
    }

    auto * output_tensor = cgraph->nodes[cgraph->n_nodes - 1];
    compute_params.output_len = output_tensor->ne[1];
    {
        for (int i = 0; i < cgraph->n_nodes; i++) {
            const auto * node = cgraph->nodes[i];
            if (node->op == GGML_OP_GET_ROWS && is_output_idx(node->src[1], node)) {
                compute_params.output_len = node->src[1]->ne[0];
                break;
            }
        }
    }
    // for NPU, output_len is always 1 except for llama-perplexity
    if (is_static && compute_params.output_len == 0) {
        compute_params.output_len = 1;
    }
    // A sliced static prefill attends a power-of-two number of KV rows: every attended size needs its own compiled
    // prefill model, so a growing sequence compiles one when the attended length doubles, not for each ubatch.
    // Rounding up adds masked rows, which cost prefill time, so it stops at the next power of two.
    if (is_static && ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1 &&
        !model_params.is_cacheless_attn && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) {
        compute_params.attention_size =
            ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq);
    }
    // The GPU plugin keeps device memory for each KV length it sees, and llama.cpp grows the KV length in steps of
    // 256. Round it up to a power of two the same way, so that a long context uses a few lengths and not one per
    // step. The KQ mask input is padded to this length with -inf (convert_ggml_input_to_ov).
    if (!is_static && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") &&
        !compute_params.mask_name.empty() && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) {
        compute_params.attention_size =
            ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq);
    }
    model_params.ctx = model_params.ctx_per_seq * model_params.n_seq;
    return {model_params, compute_params};
}

void GgmlOvDecoder::validate_cgraph() const {
    if (m_model_params.n_seq > 1 && m_is_static == true) {
        throw std::runtime_error("n_seq > 1 is not supported on NPU. Try setting -np 1.");
    }
}

bool GgmlOvDecoder::has_inp_embd_leaf_use(const ggml_tensor * tensor) const {
    for (int i = 0; i < m_cgraph->n_nodes; i++) {
        if (is_inp_embd_leaf(tensor, m_cgraph->nodes[i])) {
            return true;
        }
    }
    return false;
}

ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
                                                      const ggml_tensor * input,
                                                      int dynamic_dim_index) const {
    if (m_naive) {
        return input != nullptr ? ov::PartialShape{get_shape(input)} : ov::PartialShape{get_shape(op)};
    }
    const std::string name = input != nullptr ? std::string(input->name) : std::string();
    ov::PartialShape input_shape;

    if (is_inp_tok(input, op) || is_inp_pos(input, op)) {
        // tokens or positions
        int len = m_is_static ? (m_is_prefill ? m_prefill_chunk_size : 1) : -1;
        if (m_is_static && is_inp_pos(input, op)) {
            // IMROPE stacks n_planes (t/h/w/e) position planes back to back
            len *= get_inp_pos_n_planes(op);
        }
        input_shape = ov::PartialShape{1, 1, 1, len};

    } else if (is_output_idx(input, op)) {
        // output index
        input_shape = ov::PartialShape{1, 1, 1, m_is_static ? m_compute_params.output_len : -1};

    } else if (!m_is_static && is_activation_input(input, op)) {
        input_shape = ov::PartialShape{1, 1, -1, input->ne[0]};

    } else if (is_inp_mean(input, op)) {
        input_shape = m_is_static ? ov::PartialShape{1, 1, input->ne[1], m_prefill_chunk_size} :
                                    ov::PartialShape{1, 1, -1, -1};

    } else if (is_inp_scale_rows(input, op)) {
        input_shape = ov::PartialShape{1, 1, m_is_static ? (m_is_prefill ? m_prefill_chunk_size : 1) : -1, 1};

    } else if (is_inp_mask(input, op)) {
        // mask
        if (m_is_static) {
            // The sliding-window mask spans the window cache, which is smaller than the context once
            // the context exceeds n_swa + n_ubatch (gemma-4 at -c 4096 -ub 1024: 1536 vs 4096 cells).
            // Both masks are named "attn_inp_kq_mask", so tell them apart by tensor identity.
            const bool swa_mask = is_swa_mask(input);
            int attention_size = swa_mask ? m_model_params.ctx_per_seq_swa * m_model_params.n_seq : m_model_params.ctx;
            const bool kv_window =
                m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0;
            if (kv_window) {
                attention_size = swa_mask ? m_compute_params.attention_size_swa : m_compute_params.attention_size;
            }
            input_shape = ov::PartialShape{1, 1, m_is_prefill ? m_prefill_chunk_size : 1, attention_size};
        } else if (m_is_stateful) {
            input_shape = ov::PartialShape{1, 1, -1, -1};
        } else {
            input_shape = ov::PartialShape{-1, 1, -1, -1};
        }

    } else if (is_recurrent_cache(input)) {
        input_shape = ov::PartialShape{get_shape(input)};
        if (!m_is_static && !m_is_stateful && input->ne[1] > 1) {
            input_shape[2] = -1;
        }

    } else if (is_kvcache(input, op)) {
        // kvcache
        input_shape = ov::PartialShape{get_shape(input)};
        // Whisper.cpp uses a fixed size 1D KV buffer [N, 1, 1, 1] (GGML) or [1, 1, 1, N] (OV).
        // the token fill level is handled by token_len_per_seq + dynamic mask input.
        // skip dynamic dim and stateful reshape for this layout.
        const bool is_flat_kv = (input->ne[1] == 1 && input->ne[2] == 1 && input->ne[3] == 1);
        if (!m_is_static && !is_flat_kv) {
            // do not fix ctx size to make llama-bench work across test params
            input_shape[2] = -1;
        } else if (m_is_prefill ? ggml_openvino_kv_slice_enabled() :
                                  m_is_static && ggml_openvino_npu_decode_bucket() > 0) {
            const auto layer = extract_layer_from_name(name);
            if (layer.has_value() && !is_swa_layer(*layer) && m_compute_params.attention_size > 0 &&
                m_compute_params.attention_size < input_shape[2].get_length()) {
                const int attention_size = m_compute_params.attention_size;
                input_shape[2] = attention_size;
            }
            if (layer.has_value() && !is_swa_layer(*layer) && ggml_openvino_npu_kv_head_major_enabled()) {
                GGML_ASSERT(input_shape[1].get_length() == 1);
                const int64_t heads = get_n_heads_kv_for_tensor(input);
                const int64_t head_size = input_shape[3].get_length() / heads;
                input_shape = name.rfind("cache_v_l", 0) == 0 ?
                                  ov::PartialShape{1, heads, head_size, input_shape[2]} :
                                  ov::PartialShape{1, heads, input_shape[2], head_size};
            }
        }
        if ((is_stateful() && !is_flat_kv) || is_kvcache_4d(input)) {
            // Convert stateless KV cache layout [1, 1, seq, n_heads_kv * head_size]
            // to stateful layout [1, seq, n_heads_kv, head_size]. Stateless GPU graphs use the same
            // layout for the caches that qualify (see is_kvcache_4d), bound over the same memory.
            // NOTE: Gemma4 uses per-layer-type KV shapes, so no single scalar describes every
            // layer. E2B varies only the head size (sliding 256, full 512); 12B also varies the
            // head COUNT (sliding 8 x 256, full 1 x 512). Take the head count for this tensor's
            // own layer type and derive the head size from its own combined dim, so both layer
            // types get the correct split. Using the model-level count split 12B's sliding
            // states as 1 x 2048 and decoded garbage.
            assert(input_shape.size() == 4 && input_shape[0] == 1 && input_shape[1] == 1 &&
                   input_shape[2].is_dynamic() && input_shape[3].is_static());
            const int n_heads_kv = get_n_heads_kv_for_tensor(input);
            assert(n_heads_kv > 0 && input_shape[3].get_length() % n_heads_kv == 0);
            const int64_t combined_dim = input_shape[3].get_length();  // n_heads_kv * head_size
            const int64_t head_size = combined_dim / n_heads_kv;
            input_shape = {input_shape[0], ov::Dimension::dynamic(), n_heads_kv, head_size};
        }

    } else if (is_kv_idx(input, op)) {
        // kv update index
        int len = m_is_static ? (m_is_prefill ? m_prefill_chunk_size : 1) : -1;
        input_shape = ov::PartialShape{1, 1, 1, len};

    } else if (is_inp_s_copy(input, op) || is_s_copy_leaf(input)) {
        // On NPU the total slot count (n_seq_max) is fixed at translation time, so the s_copy
        // index list has a static length; on CPU/GPU it may change across compiles (defrag).
        input_shape = m_is_static ? ov::PartialShape{get_shape(input)} : ov::PartialShape{1, 1, 1, -1};

    } else if (input != nullptr && op != nullptr && (is_inp_emb(input, op) || has_inp_embd_leaf_use(input))) {
        input_shape = ov::PartialShape{get_shape(input)};
        if (!m_is_static) {
            input_shape[2] = -1;
        }
    }
    else {
        input_shape = ov::PartialShape{get_shape(input)};
    }
    // A static graph (NPU) keeps the fixed token count set above; only a split static graph, whose parts are
    // fed by other backends, marks the dimension dynamic. Without this the token dimension of inp_tokens becomes
    // dynamic in the NPU graph (and, for example, the GATED_DELTA_NET pad masking fails).
    if (dynamic_dim_index != -1 && (!m_is_static || m_model_is_splitted)) {
        input_shape[3 - dynamic_dim_index] = -1;
    }
    if (op->op == GGML_OP_SOFT_MAX && op->src[1] != nullptr && op->src[1]->op == GGML_OP_NONE &&
        op->src[1]->flags & GGML_TENSOR_FLAG_INPUT && op->src[1] == input) {
        // for softmax input mask, the shape is [1, 1, seq_active, seq_active], where seq_active is determined by the input active sequence length instead of the kv cache sequence length
        if (m_is_static) {
            const int64_t seq_active = m_is_prefill ? m_prefill_chunk_size : 1;
            input_shape[2] = seq_active;
            input_shape[3] = seq_active;
        } else {
            input_shape[2] = -1;
            input_shape[3] = -1;
        }
    }
    return input_shape;
}

bool GgmlOvDecoder::is_s_copy_leaf(const ggml_tensor * tensor) const {
    if (tensor == nullptr || tensor->op != GGML_OP_NONE || m_cgraph == nullptr) {
        return false;
    }
    for (int i = 0; i < m_cgraph->n_nodes; i++) {
        const ggml_tensor * node = m_cgraph->nodes[i];
        if (node->op != GGML_OP_GET_ROWS || node->src[0] == nullptr || node->src[1] == nullptr) {
            continue;
        }
        // The index list may reach the s_copy leaf through one or more VIEWs.
        const ggml_tensor * idx = node->src[1];
        while (idx != nullptr && idx->op == GGML_OP_VIEW) {
            idx = idx->src[0];
        }
        if (idx != tensor) {
            continue;
        }
        // The gathered data must be a recurrent state cache (cache_r/cache_s).
        const ggml_tensor * data = node->src[0];
        while (data != nullptr && (data->op == GGML_OP_VIEW || data->op == GGML_OP_RESHAPE)) {
            data = data->src[0];
        }
        if (data != nullptr && is_recurrent_cache(data)) {
            return true;
        }
    }
    return false;
}

void GgmlOvDecoder::add_extra_inputs() {
    m_model_extra_inputs.clear();

    // Extra inputs:
    // 1. `attention_size`, used in FLASH_ATTN where the shape of the matmul's are 256 aligned,
    //     see llama_kv_cache_unified::get_n_kv and llama_kv_cache_unified::get_padding.
    // 2. `n_seq_active` and `seq_active_start`, used in FLASH_ATTN_EXT to indicate the active sequences in the batch

    auto create_1d_input = [this](const std::string & name, int64_t value, bool force_parameter = false) {
        m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1}, value, force_parameter || !m_is_static, {}, -1};
    };

    if (m_compute_params.attention_size != -1) {
        create_1d_input("attention_size", m_compute_params.attention_size);
    }
    if (m_compute_params.attention_size_static != -1) {
        create_1d_input("attention_size_static", m_compute_params.attention_size_static);
    }
    if (m_compute_params.attention_size_swa != -1) {
        create_1d_input("attention_size_swa", m_compute_params.attention_size_swa);
    }
    // only the stateful SWA mask consumes this
    if (is_stateful() && m_compute_params.swa_window != -1) {
        create_1d_input("swa_window", m_compute_params.swa_window);
    }
    create_1d_input("n_seq_active", m_compute_params.n_seq_active);
    create_1d_input("seq_active_start", m_compute_params.seq_active_start);
    create_1d_input("seq_active_end", m_compute_params.seq_active_start + m_compute_params.n_seq_active);
    if (m_compute_params.token_len_per_seq != -1) {
        create_1d_input("token_len_per_seq", m_compute_params.token_len_per_seq);
    }
    if (m_is_static && m_is_prefill && ggml_openvino_npu_hfa_prefill_enabled()) {
        if (m_compute_params.n_seq_active != 1) {
            throw std::runtime_error("GGML_OPENVINO_NPU_HFA_PREFILL currently requires one active sequence");
        }
        if (!m_model_params.swa_layers.empty()) {
            throw std::runtime_error("GGML_OPENVINO_NPU_HFA_PREFILL does not yet support sliding-window layers");
        }
        const auto chunk_size = static_cast<size_t>(m_prefill_chunk_size);
        const auto input_len = static_cast<size_t>(m_compute_params.input_len);
        const auto num_chunks = (input_len + chunk_size - 1) / chunk_size;
        // Head-major KV: the past is the whole cache storage [1, heads, attention_size, head_size].
        const bool head_major = ggml_openvino_npu_kv_head_major_enabled();
        const auto past_capacity = head_major ? static_cast<size_t>(m_compute_params.attention_size) :
                                                std::max(chunk_size, (num_chunks - 1) * chunk_size);
        for (const auto & [kv_name, kv_tensor] : m_inputs) {
            if (kv_name.rfind("cache_k_l", 0) != 0 && kv_name.rfind("cache_v_l", 0) != 0) {
                continue;
            }
            const auto n_heads_kv = static_cast<size_t>(get_n_heads_kv_for_tensor(kv_tensor));
            const auto combined_dim = static_cast<size_t>(kv_tensor->ne[0]);
            GGML_ASSERT(n_heads_kv > 0 && combined_dim % n_heads_kv == 0);
            const auto head_size = combined_dim / n_heads_kv;
            // flash_attn_ext looks the past input up by layer, so drop the graph-ordinal suffix ("#l12").
            const std::string cache_name = kv_name.substr(0, kv_name.find('#'));
            const bool v_transposed = head_major && kv_name.rfind("cache_v_l", 0) == 0;
            m_model_extra_inputs["ggml_hfa_past_" + cache_name] = {
                get_ov_type(kv_tensor),
                v_transposed ? ov::Shape{1, n_heads_kv, head_size, past_capacity} :
                head_major   ? ov::Shape{1, n_heads_kv, past_capacity, head_size} :
                               ov::Shape{1, past_capacity, n_heads_kv, head_size},
                0, true, {}, -1};
        }
        m_model_extra_inputs["ggml_hfa_mask"] = {
            ov::element::f16, ov::Shape{1, 1, chunk_size, past_capacity + chunk_size}, 0, true, {}, -1};
    }
    // create_1d_input("token_len", m_compute_params.token_len_per_seq * m_compute_params.n_seq_active);

    // n_seq_active and attention_size(_swa) are dimensions of the KQ masks. Read them from the mask shape inside the
    // model: the GPU plugin then gets the Q Reshape and KV Slice shapes from shape inference instead of waiting for
    // the input values on the device
    if (!m_is_static && !m_is_stateful && ggml_openvino_shape_from_mask_enabled()) {
        auto from_mask = [this](const std::string & name, const std::string & mask, int64_t axis) {
            auto it = m_model_extra_inputs.find(name);
            if (it != m_model_extra_inputs.end() && !mask.empty() && m_model_inputs.count(mask) != 0) {
                it->second.shape_source = mask;
                it->second.shape_axis = axis;
            }
        };
        const auto & full = m_compute_params.mask_name;
        const auto & swa = m_compute_params.mask_swa_name;
        from_mask("attention_size", full, 3);
        from_mask("attention_size_swa", swa, 3);
        from_mask("n_seq_active", full.empty() ? swa : full, 0);
    }

    if (m_compute_params.cache_rs_reset_idx != -1) {
        // Whether/which cache slot to reset varies per compute call (e.g. a new sequence starting
        // vs. continued decoding). can_reuse_statically() does not invalidate the cached static
        // model on ComputeParams changes, so these must stay runtime Parameters even when static
        // (translate_recurrent_cache_reset only uses them in value comparisons, never as Slice bounds, so this
        // does not reintroduce dynamic shapes).
        create_1d_input("cache_rs_reset_idx", m_compute_params.cache_rs_reset_idx, /*force_parameter=*/true);
        create_1d_input("cache_rs_reset_len", m_compute_params.cache_rs_reset_len, /*force_parameter=*/true);
    }

    if (m_compute_params.s_copy_active_slot_len != -1) {
        create_1d_input("s_copy_active_slot_len", m_compute_params.s_copy_active_slot_len);
        if (m_model_inputs.count("rs_active_rows") != 0) {
            // The row-map prefix is rebound with its current length on every compute.
            // Shape consumers must not wait for a scalar uploaded to the GPU.
            auto & active = m_model_extra_inputs.at("s_copy_active_slot_len");
            active.shape_source = "rs_active_rows";
            active.shape_axis = 3;
        }
        if (m_is_static) {
            // Number of real tokens in the current prefill chunk. The last chunk is padded with
            // fabricated token ids; attention masks them out, but the recurrent (GDN/conv) path
            // would otherwise fold them into cache_r/cache_s permanently. Varies per chunk, so it
            // must stay a runtime Parameter; it is only compared against a Range or used as Gather
            // indices, so it does not make any shape dynamic.
            create_1d_input("chunk_valid_len", get_static_n_tokens(), /*force_parameter=*/true);
        }
    }

    for (const auto & [node_name, writeback] : m_compute_params.rs_writebacks) {
        create_1d_input("rs_slot_begin_" + node_name, writeback.slot_begin);
        if (!m_is_static && writeback.src_begin >= 0) {
            create_1d_input("rs_src_begin_" + node_name, writeback.src_begin);
        }
        if (writeback.seq_count >= 0) {
            create_1d_input("rs_seq_count_" + node_name, writeback.seq_count);
            create_1d_input("rs_snapshot_stride_" + node_name, writeback.snapshot_stride);
        }
        if (writeback.window_count >= 0) {
            create_1d_input("rs_window_count_" + node_name, writeback.window_count);
        }
    }
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
    m_compute_params.recurrent_controls.clear();
    // Naive graphs have no full-model cache fusion and node cases are not initialized here.
    if (!m_naive && !m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() &&
        !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) {
        for (int i = 0; i < m_cgraph->n_nodes; ++i) {
            const auto node = m_cgraph->nodes[i];
            const auto op_case = m_node_info_list[i].node_op_case;
            if (node->op == GGML_OP_CPY && (op_case == 10 || op_case == 12)) {
                m_model_extra_inputs["rs_update_" + get_tensor_ov_name(m_cgraph, node)] =
                    {ov::element::i64, ov::Shape{1, 1, 1, 4}, 0, true, {}, -1};
            }
        }
        for (const auto & [name, write] : m_compute_params.rs_writebacks) {
            if (write.src_begin >= 0) {
                auto & values = m_compute_params.recurrent_controls["rs_offsets_" + name];
                values = {write.slot_begin, write.src_begin};
                m_model_extra_inputs["rs_offsets_" + name] =
                    {ov::element::i64, ov::Shape{1, 1, 1, 2}, 0, true, {}, -1};
            }
        }
        for (int i = 0; i < m_cgraph->n_nodes; ++i) {
            const auto concat = m_cgraph->nodes[i];
            if (concat->op != GGML_OP_CONCAT || !concat->src[0] || concat->src[0]->op != GGML_OP_RESHAPE ||
                !concat->src[0]->src[0] || concat->src[0]->src[0]->op != GGML_OP_VIEW ||
                concat->src[0]->src[0]->src[0]->op != GGML_OP_GET_ROWS) {
                continue;
            }
            std::vector<int64_t> values;
            for (int j = i + 1; j < m_cgraph->n_nodes; ++j) {
                const auto write = m_cgraph->nodes[j];
                if ((is_conv_state_writeback(write) || is_conv_state_snapshot_writeback(write)) &&
                    write->src[0]->src[0] == concat) {
                    const auto it = m_compute_params.rs_writebacks.find(get_tensor_ov_name(m_cgraph, write));
                    if (it == m_compute_params.rs_writebacks.end()) {
                        values.clear();
                        break;
                    }
                    const auto & wb = it->second;
                    const int64_t count = wb.window_count >= 0 ? wb.window_count : 1;
                    for (int64_t w = 0; w < count; ++w) {
                        values.push_back(wb.src_begin + w);
                        values.push_back(wb.slot_begin + (count - 1 - w) *
                                                          (wb.window_count >= 0 ? wb.snapshot_stride : 0));
                    }
                    break;
                }
            }
            if (!values.empty()) {
                const auto name = "rs_windows_" + get_tensor_ov_name(m_cgraph, concat);
                m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1, 1, values.size() / 2, 2}, 0, true, {}, -1};
                m_compute_params.recurrent_controls[name] = std::move(values);
            }
        }
    }
#endif
    if (!m_is_static && !m_compute_params.sampling_rows.empty()) {
        m_model_extra_inputs["sampling_rows"] =
            {ov::element::i64, ov::Shape{m_compute_params.sampling_rows.size()}, 0, true, {}, -1};
    } else {
        for (const auto & [node_name, row] : m_compute_params.sampling_rows) {
            create_1d_input("sampling_row_" + node_name, row);
        }
    }
    for (const auto & [node_name, rows] : m_compute_params.gdn_attention_rows) {
        create_1d_input("gdn_attention_rows_" + node_name, rows);
    }
}

bool GgmlOvDecoder::node_is_used_as_src(const int node_idx) {
    ggml_tensor * node = m_cgraph->nodes[node_idx];
    for (int i = node_idx; i < m_cgraph->n_nodes; i++) {
        ggml_tensor * other_node = m_cgraph->nodes[i];
        for (int j = 0; j < GGML_MAX_SRC; j++) {
            if (other_node->src[j] == node) {
                return true;
            }
        }
    }
    return false;
}

void GgmlOvDecoder::compute_model_inputs() {
    m_model_inputs.clear();
    m_inputs.clear();
    m_kvcache_4d.clear();
    // remember the KV caches that get_graph_input_shape gave the 4-D layout, so that they are bound with that shape
    auto note_kvcache_4d = [this](const ggml_tensor * input, const ggml_tensor * op, const ov::PartialShape & shape) {
        if (!m_is_stateful && is_kvcache(input, op) && shape.rank().is_static() && shape.rank().get_length() == 4 &&
            shape[1].is_dynamic()) {
            m_kvcache_4d.insert(input);
        }
    };
    for (int i = 0; i < m_cgraph->n_nodes; i++) {
        ggml_tensor * node = m_cgraph->nodes[i];
        // the node op is NONE means this node maybe as input of later nodes, we should add it to model inputs for this node.
        if (node->op == GGML_OP_NONE && node_is_used_as_src(i)) {
            std::string node_name = get_tensor_ov_name(m_cgraph, node);
            if (m_model_weights.find(node_name) == m_model_weights.end()) {
                m_inputs[node_name] = node;
                m_model_inputs[node_name] = {get_ov_type(node),
                                             get_graph_input_shape(node, nullptr, m_node_dynamic_dims[node])};
                note_kvcache_4d(node, nullptr, m_model_inputs[node_name].shape);
            }
            continue;
        }
        for (int i = 0; i < GGML_MAX_SRC; i++) {
            auto * src = node->src[i];
            if (src == nullptr) {
                continue;
            }
            std::string src_name = get_tensor_ov_name(m_cgraph, src);
            if (src->flags & GGML_TENSOR_FLAG_INPUT) {
                src_name = get_tensor_graph_input_ov_name(this, m_cgraph, src, node);
            }
            // ROPE frequency factors (rope_factors_short/long in Phi-3, Phi-4 and MiniCPM) are registered as
            // "rope_freqs.weight" in create_weight_nodes(). Without the same name here they become a
            // Parameter fed from the host weight buffer, which is empty in cache-only mode and after
            // GGML_OPENVINO_RELEASE_WEIGHTS.
            if (is_rope_freqs_weight(src->view_src ? src->view_src : src, node)) {
                src_name = "rope_freqs.weight";
            }
            if (m_model_weights.find(src_name) != m_model_weights.end()) {
                continue;
            }
            // A view over a weight is served by the base tensor's Constant, never by a Parameter.
            if (src->view_src != nullptr &&
                m_model_weights.find(get_tensor_ov_name(m_cgraph, src->view_src)) != m_model_weights.end()) {
                continue;
            }

            bool is_intermediate_node = false;
            for (const auto & node_info : m_node_info_list) {
                if (node_info.node == src) {
                    is_intermediate_node = true;
                    break;
                }
            }
            if (is_intermediate_node) {
                continue;
            }
            if (m_model_inputs.find(src_name) != m_model_inputs.end()) {
                continue;
            }

            m_inputs[src_name] = src;

            ggml_backend_buffer * buffer = src->buffer;
            // GGML_BACKEND_BUFFER_USAGE_ANY are kv caches
            if (buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY) {
                if (auto it = std::find(m_model_params.kv_names.begin(), m_model_params.kv_names.end(), src_name);
                    it == m_model_params.kv_names.end()) {
                    m_model_params.kv_names.push_back(src_name);
                }
            }
            // Resolve nested VIEW nodes by following src[0] until the first non-VIEW tensor.
            while (src->op == GGML_OP_VIEW && src->src[0] != nullptr) {
                src = src->src[0];
                src_name = get_tensor_ov_name(m_cgraph, src);
            }
            m_inputs[src_name] = src;
            m_model_inputs[src_name] = {get_ov_type(src),
                                        get_graph_input_shape(node, src, m_node_dynamic_dims[src])};
            note_kvcache_4d(src, node, m_model_inputs[src_name].shape);
        }
    }
    if (!m_naive && !m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() &&
        m_compute_params.s_copy_active_slot_len > 0) {
        const ggml_tensor * rows = nullptr;
        for (const auto & [name, tensor] : m_inputs) {
            if (tensor->type == GGML_TYPE_I32 && is_s_copy_leaf(tensor)) {
                if (rows && rows != tensor) {
                    return;  // Different recurrent row maps cannot share one active shape.
                }
                rows = tensor;
            }
        }
        if (rows && m_compute_params.s_copy_active_slot_len <= ggml_nelements(rows)) {
            m_inputs["rs_active_rows"] = const_cast<ggml_tensor *>(rows);
            m_model_inputs["rs_active_rows"] = {ov::element::i32, ov::PartialShape{1, 1, 1, -1}};
        }
    }
}

void GgmlOvDecoder::compute_model_outputs() {
    m_model_outputs.clear();
    m_model_output_names.clear();
    for (int node_n = 0; node_n < m_cgraph->n_nodes; node_n++) {
        auto * cur_node = m_cgraph->nodes[node_n];
        // if the node op is NONE means this node is not used at all, we can skip it directly without adding to model outputs.
        if (cur_node->op == GGML_OP_NONE || cur_node->op == GGML_OP_VIEW || cur_node->op == GGML_OP_RESHAPE) {
            continue;
        }
        const bool runtime_recurrent_write = !m_naive && is_recurrent_cache(cur_node->view_src) &&
                                              ::is_inplace_op(cur_node) &&
                                              (is_recurrent_cache_reset(cur_node) || !m_is_static);
        if (::is_inplace_op(cur_node) && ggml_nbytes(cur_node) == 0 && !runtime_recurrent_write) {
            continue;
        }
        const bool inactive_top_k = is_sampling_top_k(cur_node) && !(cur_node->flags & GGML_TENSOR_FLAG_COMPUTE);
        auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)];
        // llama flags result_norm in every graph but reads it only with embeddings on, when it has no consumer
        // and is kept by the rule below.
        const bool unread_embd = strcmp(cur_node->name, "result_norm") == 0 && cur_node_use_count > 0;
        if (((cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) && !unread_embd) || inactive_top_k) {
            const auto name = get_tensor_ov_name(m_cgraph, cur_node);
            m_model_outputs[name] = cur_node;
            m_model_output_names.insert(name);
        }
        if (is_gdn_snapshot_writeback(cur_node)) {
            auto * cache = cur_node->view_src;
            const auto name = get_tensor_ov_name(m_cgraph, cache);
            m_model_outputs[name] = cache;
            m_model_output_names.insert(name);
        }
        if (is_ssm_state_writeback(cur_node)) {
            auto * cache = cur_node->view_src;
            const auto name = get_tensor_ov_name(m_cgraph, cache);
            m_model_outputs[name] = cache;
            m_model_output_names.insert(name);
        }
        if (cur_node_use_count == 0) {
            // The output of in-place ops is the view_src tensor, which is updated in place. We should use the view_src name as the output name to make sure it can be correctly matched with the later ops that use the view_src.
            if (cur_node != nullptr && ::is_inplace_op(cur_node) &&
                (ggml_nbytes(cur_node) > 0 || runtime_recurrent_write)) {
                cur_node = cur_node->view_src;
            }
        } else {
            int input_use_count = 0;
            for (int i = 0; i < m_cgraph->n_nodes; i++) {
                ggml_tensor * node = m_cgraph->nodes[i];
                for (int j = 0; j < GGML_MAX_SRC; j++) {
                    if (node->src[j] != NULL && node->src[j] == cur_node) {
                        input_use_count++;
                    }
                }
            }
            // op tests (the naive path) can read any node of the graph, e.g. the intermediate sum of a fused
            // ADD + RMS_NORM + MUL, so every non-in-place node is a model output there
            if (input_use_count == cur_node_use_count && (!m_naive || ::is_inplace_op(cur_node))) {
                cur_node = nullptr;
            }
        }
        if (cur_node != nullptr) {
            std::string cur_node_name = get_tensor_ov_name(m_cgraph, cur_node);
            m_model_outputs[cur_node_name] = cur_node;
            m_model_output_names.insert(cur_node_name);
        }
    }
}

const ggml_tensor * GgmlOvDecoder::get_tensor_used_op(const ggml_tensor * tensor) const {
    if (tensor == nullptr) {
        return nullptr;
    }
    for (int i = 0; i < m_cgraph->n_nodes; i++) {
        const auto * node = m_cgraph->nodes[i];
        for (int j = 0; j < GGML_MAX_SRC; j++) {
            if (node->src[j] == tensor) {
                return node;
            }
        }
    }
    return nullptr;
}

bool GgmlOvDecoder::is_kvcache_4d(const ggml_tensor * cache) const {
    static const bool enabled = ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_KV_4D") > 0;
    if (!enabled || m_is_static || m_is_stateful || m_model_is_splitted || !ggml_openvino_is_gpu()) {
        return false;
    }
    // `-fa off` (transposed V cache): keep the [1, 1, ctx, n_heads_kv * head_size] layout. The 4-D K cache breaks the
    // MUL_MAT attention of the Phi-3 models (Phi-3.5 mini, Phi-4 mini), and the soft-capped manual attention of
    // gemma-2 with `-fa on` ("could not construct a memory descriptor using strides" in the GPU plugin's oneDNN path).
    if (m_model_params.v_trans || m_model_params.softcap_attn) {
        return false;
    }
    if (cache->op != GGML_OP_NONE || cache->view_src != nullptr || !is_kvcache(cache, nullptr)) {
        return false;
    }
    // one sequence, [n_heads_kv * head_size, ctx, 1, 1]; whisper's flat KV buffer has ctx == 1
    if (cache->ne[1] <= 1 || cache->ne[2] != 1 || cache->ne[3] != 1) {
        return false;
    }
    const int n_heads_kv = get_n_heads_kv_for_tensor(cache);
    if (n_heads_kv <= 0 || cache->ne[0] % n_heads_kv != 0) {
        return false;
    }
    // check the nodes that take the cache itself as a source (views of those views, such as the PERMUTE of the read
    // VIEW, are checked through them)
    auto feeds_only_permutes = [this](const ggml_tensor * view) {
        for (int i = 0; i < m_cgraph->n_nodes; i++) {
            const auto * node = m_cgraph->nodes[i];
            for (int j = 0; j < GGML_MAX_SRC; j++) {
                if (node->src[j] == view && node->op != GGML_OP_PERMUTE) {
                    return false;
                }
            }
        }
        return true;
    };
    for (int i = 0; i < m_cgraph->n_nodes; i++) {
        const auto * node = m_cgraph->nodes[i];
        bool uses_cache = false;
        for (int j = 0; j < GGML_MAX_SRC; j++) {
            uses_cache = uses_cache || node->src[j] == cache;
        }
        if (!uses_cache) {
            continue;
        }
        // write: whole rows into the cache itself
        if (node->op == GGML_OP_SET_ROWS && node->src[2] == cache && node->src[0]->ne[0] == cache->ne[0]) {
            continue;
        }
        // read: the first rows of the cache, each row split into heads, permuted for attention
        if (node->op == GGML_OP_VIEW && node->src[0] == cache && node->view_offs == 0 &&
            node->ne[0] * node->ne[1] == cache->ne[0] && node->nb[2] == cache->nb[1] && node->ne[3] == 1 &&
            feeds_only_permutes(node)) {
            continue;
        }
        return false;
    }
    return true;
}

bool GgmlOvDecoder::is_kvcache_token_rows(const ggml_tensor * cache) const {
    for (int i = 0; i < m_cgraph->n_nodes; i++) {
        const auto * node = m_cgraph->nodes[i];
        if (node->op != GGML_OP_SET_ROWS) {
            continue;
        }
        // SET_ROWS writes whole rows of src[2], which is the cache or a view of it
        const auto * dst = node->src[2];
        if (dst != nullptr && (dst == cache || dst->view_src == cache) && dst->ne[0] != cache->ne[0]) {
            return false;
        }
    }
    return true;
}

const ggml_tensor * GgmlOvDecoder::get_tensor_from_name(const std::string & name) const {
    for (int i = 0; i < m_cgraph->n_nodes; i++) {
        const auto * node = m_cgraph->nodes[i];
        for (int j = 0; j < GGML_MAX_SRC; j++) {
            const auto * src = node->src[j];
            if (src == nullptr) {
                break;
            }
            if (get_tensor_ov_name(m_cgraph, src) == name) {
                return src;
            }
        }
    }
    return nullptr;
}

std::string GgmlOvDecoder::get_hfa_history_input_name() const {
    for (const auto & [name, tensor] : m_inputs) {
        const auto * op = get_tensor_used_op(tensor);
        if (op != nullptr && is_inp_pos(tensor, op)) {
            return name;
        }
    }
    throw std::runtime_error("HFA prefill position input was not found");
}

std::map<std::string, std::string> GgmlOvDecoder::get_kv_param_res_names() const {
    std::map<std::string, std::string> kv_param_res_names;
    for (const auto & name : m_model_params.kv_names) {
        kv_param_res_names[name] = name;
    }
    return kv_param_res_names;
}

// MUL_MAT_ID's src[0] is the [k, m, n_expert] expert-weight tensor. It is always a constant per-expert
// weight table -- never a computed activation -- regardless of whether the backend happened to mark its
// buffer as GGML_BACKEND_BUFFER_USAGE_WEIGHTS (test-backend-ops, for example, never sets that usage
// flag, unlike real inference). Without this, non-quantized (F16/F32/BF16) expert weights would fall
// through the check below as "not a weight", get decoded as a Parameter/activation instead of a
// Constant, and crash GatherMatmul's "only constant weights are supported" check.
static bool is_mul_mat_id_expert_weight(const ggml_tensor * node, int src_index) {
    return node->op == GGML_OP_MUL_MAT_ID && src_index == 0;
}

std::map<std::string, std::shared_ptr<ov::Node>> GgmlOvDecoder::create_weight_nodes(ggml_cgraph * cgraph, bool naive) {
    std::map<std::string, std::shared_ptr<ov::Node>> model_weights;
    auto * nodes = cgraph->nodes;
    auto n_nodes = cgraph->n_nodes;
    for (int node_i = 0; node_i < n_nodes; node_i++) {
        auto * node = nodes[node_i];
        for (int i = 0; i < GGML_MAX_SRC; i++) {
            auto * src = node->src[i];
            if (src == nullptr) {
                continue;
            }

            // A view over a weight is served by the base tensor's Constant.
            ggml_tensor * base = src->view_src ? src->view_src : src;
            std::string src_name = get_tensor_ov_name(cgraph, base);
            if (is_rope_freqs_weight(base, node)) {
                src_name = "rope_freqs.weight";
            }
            ggml_backend_buffer * buffer = base->buffer;
            if (buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS || ggml_is_quantized(base->type) ||
                is_mul_mat_id_expert_weight(node, i)) {
                if (model_weights.find(src_name) == model_weights.end()) {
                    auto weight_node = create_weight_node(base, naive);
                    weight_node->set_friendly_name(src_name);
                    model_weights[src_name] = weight_node;
                }
            }
        }
    }
    return model_weights;
}

// Process-lifetime cache for weight nodes built from NON-OpenVINO buffers (e.g. the
// token_embd.weight copy that lives in a CPU/mmap buffer and feeds GET_ROWS). Such
// tensors have no OV buffer context to own a cached extra, so without this they are
// re-extracted/re-requantized on every (re)compile — for token_embd that is a ~1-2 GB
// F32 dequant each time. Keyed by tensor->data, which is stable for the process and
// uniquely identifies the immutable weight bytes. OV-buffer weights keep using the
// per-tensor extra cache and never reach here.
static std::mutex g_nonov_weight_cache_mutex;
static std::unordered_map<const void *, std::shared_ptr<ov::Node>> g_nonov_weight_cache;

std::set<std::string> GgmlOvDecoder::collect_weight_names(ggml_cgraph * cgraph) {
    // Mirrors the name-selection logic of create_weight_nodes() but builds no nodes,
    // so topology checks don't trigger weight extraction/requantization.
    std::set<std::string> names;
    for (int node_i = 0; node_i < cgraph->n_nodes; node_i++) {
        auto * node = cgraph->nodes[node_i];
        for (int i = 0; i < GGML_MAX_SRC; i++) {
            auto * src = node->src[i];
            if (src == nullptr) {
                continue;
            }
            const ggml_tensor * base = src->view_src ? src->view_src : src;
            std::string src_name(base->name);
            if (is_rope_freqs_weight(base, node)) {
                src_name = "rope_freqs.weight";
            }
            ggml_backend_buffer * buffer = base->buffer;
            if (buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS || ggml_is_quantized(base->type)) {
                names.insert(src_name);
            }
        }
    }
    return names;
}

std::shared_ptr<ov::Node> GgmlOvDecoder::create_weight_node(ggml_tensor * tensor, bool naive) {
    const bool is_ov_buffer = ggml_backend_buffer_is_openvino(tensor->buffer);

    // Check if we have a pre-built constant from the OpenVINO backend buffer
    // This is set during ggml_backend_openvino_buffer_set_tensor
    if (tensor->extra) {
        OPENVINO_ASSERT(is_ov_buffer, "Unsupported weight tensor: " + std::string(tensor->name) +
                                          " Possibly this is a cpu backend repacked quantized weights");
        // Cast to our extra base type and check the type
        auto * extra_base = static_cast<ggml_openvino_extra_base *>(tensor->extra);

        if (extra_base->type == ggml_openvino_extra_base::Type::WEIGHT) {
            // F16/F32/BF16 weight with shared-memory constant
            auto * weight_extra = static_cast<ggml_openvino_weight_extra *>(tensor->extra);
            if (weight_extra->weight_node) {
                // GGML_LOG_DEBUG("%s: using pre-built weight node for %s\n", __func__, tensor->name);
                return weight_extra->weight_node;
            }
        } else if (extra_base->type == ggml_openvino_extra_base::Type::QUANTIZED_WEIGHT) {
            // Quantized weight with pre-extracted data
            auto * quant_extra = static_cast<ggml_openvino_quantized_weight_extra *>(tensor->extra);
            if (quant_extra->weight_node) {
                // GGML_LOG_DEBUG("%s: using pre-extracted quantized weight node for %s\n", __func__, tensor->name);
                return quant_extra->weight_node;
            }
        }
    }

    // MUL_MAT_ID expert weights are 3D GGML tensors [k, m, n_expert].
    // Keep the full reversed 4D shape when materializing non-quantized constants,
    // otherwise the expert dimension is collapsed and later Gather/MatMul logic
    // only sees a single expert slice.
    if (!ggml_is_quantized(tensor->type) && (tensor->ne[2] > 1 || tensor->ne[3] > 1)) {
        auto weight_tensor = ov::Tensor(get_ov_type(tensor), get_shape(tensor), tensor->data);
        auto weight_node = std::make_shared<ov::op::v0::Constant>(weight_tensor);
        weight_node->set_friendly_name(tensor->name);
        return weight_node;
    }

    // Non-OV-buffer weights (CPU/mmap, e.g. the GET_ROWS token_embd copy) have no buffer
    // context to cache an extra in, so memoize them here keyed by their (stable) data
    // pointer to avoid re-extracting on every recompile. Opt-in via
    // GGML_OPENVINO_REDUCE_COMPILE_MEM or GGML_OPENVINO_MEMORY_OPTIMIZE. Skip
    // for `naive` (test/naive path) since use_bias changes the produced node.
    // Self-contained decode-window models are built after the pair; reusing the node keeps e.g. the
    // token_embd vocab on the pair's NPUW bank uid instead of embedding and importing a second copy.
    const bool keep_for_windows = ggml_openvino_npu_raw_weight_cache_enabled() && ggml_openvino_npu_decode_bucket() > 0;
    const bool cacheable_nonov = (ggml_openvino_reduce_compile_mem_enabled() || keep_for_windows) && !is_ov_buffer &&
                                 !naive && tensor->data != nullptr;
    if (cacheable_nonov) {
        std::lock_guard<std::mutex> lock(g_nonov_weight_cache_mutex);
        auto it = g_nonov_weight_cache.find(tensor->data);
        if (it != g_nonov_weight_cache.end()) {
            return it->second;
        }
    }

    // There are three cases where we need to create a new weight node:
    // 1. weights are in openvino_host_buffer. Weight loading to host buffer will not trigger backend_buffer_set_tensor
    // 2. weights are in cpu/cpu_mapped buffer. On token_embd.weight goes to case 1 or 2, depending on whether mmap or direct_io is used
    // 3. test-backend-ops. buffers in test-backend-ops does not set USAGE_WEIGHT so backend_buffer_set_tensor will not create weight node

    // GGML_LOG_DEBUG("%s: creating new weight node for %s\n", __func__, tensor->name);
    static const std::set<ggml_type> weight_types = {GGML_TYPE_F32,  GGML_TYPE_F16,  GGML_TYPE_BF16, GGML_TYPE_Q8_0,
                                                     GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q4_K,
                                                     GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, GGML_TYPE_MXFP4};
    if (weight_types.find(tensor->type) == weight_types.end()) {
        throw std::runtime_error("Unexpected weight tensor type: " + std::string(tensor->name) + " with type " +
                                 ggml_type_name(tensor->type));
    }

    OvWeight ov_weight;
    if (ggml_is_quantized(tensor->type)) {
        auto use_bias = naive;
        if (is_ov_buffer) {
            const bool preserve_raw = ggml_openvino_npu_raw_weight_cache_enabled();
            if (preserve_raw) {
                // A later context must fingerprint the same raw GGUF bytes before importing its
                // self-contained blob, so keep the model buffer immutable in this mode.
                ov_weight = process_weight_tensor(tensor, tensor->data, nullptr, use_bias);
            } else {
                // The regular path stores extracted weights in the model buffer. Copy raw data
                // first because input and output ranges would otherwise overlap.
                size_t raw_size = ggml_nbytes(tensor);
                std::vector<uint8_t> tmp(raw_size);
                memcpy(tmp.data(), tensor->data, raw_size);
                ov_weight = process_weight_tensor(tensor, tmp.data(), tensor->data, use_bias);
            }
        } else {
            ov_weight = process_weight_tensor(tensor, tensor->data, nullptr, use_bias);
        }
    } else {
        // For non-quantized weights (F16/F32/BF16), data is already in tensor->data.
        // process_weight_tensor will create an ov::Tensor wrapping tensor->data directly.
        ov_weight = process_weight_tensor(tensor, tensor->data, tensor->data);
    }

    ov_weight.weight_node->set_friendly_name(tensor->name);
    if (!is_ov_buffer) {
        if (cacheable_nonov) {
            std::lock_guard<std::mutex> lock(g_nonov_weight_cache_mutex);
            // Another thread may have inserted concurrently; keep the first.
            auto [it, inserted] = g_nonov_weight_cache.emplace(tensor->data, ov_weight.weight_node);
            return it->second;
        }
        return ov_weight.weight_node;
    }

    ggml_openvino_extra_base * extra;
    if (ov_weight.is_quantized()) {
        extra = new ggml_openvino_quantized_weight_extra(std::move(ov_weight.weights), std::move(ov_weight.scales),
                                                         std::move(ov_weight.zp), ov_weight.weight_node);
    } else {
        extra = new ggml_openvino_weight_extra(std::move(ov_weight.weights), ov_weight.weight_node);
    }
    ggml_openvino_buffer_register_extra(tensor, extra);

    return ov_weight.weight_node;
}

void GgmlOvDecoder::dump_cgraph(const ggml_cgraph * cgraph, std::string & filename) {
    std::ofstream file(filename);
    if (!file.is_open()) {
        std::cerr << "Failed to open file" << '\n';
        return;
    }

    file << "=== GRAPH ===\n";

    // clang-format off
    file << "n_nodes = " << cgraph->n_nodes << "\n";
    file << " " << std::setw(3) << "nodes"
                <<  std::setw(15) << "shape"
                << std::setw(20) << "op"
                << std::setw(20) << "name"
                << std::setw(3) << "    "
                << std::setw(62) << "stride"
                << std::setw(20) << "buffer_type"
                << "\n";
    for (int i = 0; i < cgraph->n_nodes; i++) {
        ggml_tensor * node = cgraph->nodes[i];

        // Get buffer type name
        const char * buf_name = "none";
        ggml_backend_buffer_t buf = node->view_src ? node->view_src->buffer : node->buffer;
        if (buf) {
            buf_name = ggml_backend_buffer_name(buf);
        }

        file << " - " << std::setw(3) << i << ": [ "
             << std::setw(5) << node->ne[0] << ", "
             << std::setw(5) << node->ne[1] << ", "
             << std::setw(5) << node->ne[2] << ", "
             << std::setw(5) << node->ne[3] << "] "
             << std::left << std::setw(20) << ggml_op_name(node->op) << std::right << " "
             << std::left << std::setw(45) << node->name << std::right
             << std::setw(2) << "[ "
             << std::setw(0) << node->nb[0] << ", "
             << std::setw(5) << node->nb[1] << ", "
             << std::setw(5) << node->nb[2] << ", "
             << std::setw(5) << node->nb[3] << "] "
             << std::right << std::setw(15) << buf_name << std::right
             << " compute=" << ((node->flags & GGML_TENSOR_FLAG_COMPUTE) != 0)
             << " output=" << ((node->flags & GGML_TENSOR_FLAG_OUTPUT) != 0)
             << " view_offs=" << node->view_offs
             << "\n";

        for (int i = 0; i < GGML_MAX_SRC; i++) {
            if (auto* src = node->src[i]) {
                // Get buffer type name for source
                const char * src_buf_name = "none";
                ggml_backend_buffer_t src_buf = src->view_src ? src->view_src->buffer : src->buffer;
                if (src_buf) {
                    src_buf_name = ggml_backend_buffer_name(src_buf);
                }

                file << std::setw(10) << " [ "
                << std::setw(5) << src->ne[0] << ", "
                << std::setw(5) << src->ne[1] << ", "
                << std::setw(5) << src->ne[2] << ", "
                << std::setw(5) << src->ne[3] << "] "
                << std::setw(12)
                << i << ": " << std::left << std::setw(12) << ggml_op_name(src->op) << std::right;
                file << std::left << std::setw(30) << src->name << std::right
                << std::setw(16) << "[ "
                << std::setw(0) << src->nb[0] << ", "
                << std::setw(5) << src->nb[1] << ", "
                << std::setw(5) << src->nb[2] << ", "
                << std::setw(5) << src->nb[3] << "] "
                << std::right << std::setw(15) << src_buf_name << std::right
                << "\n";
            }
        }
    }

    file << "n_leafs = " << cgraph->n_leafs << "\n";
    for (int i = 0; i < cgraph->n_leafs; i++) {
        ggml_tensor * node = cgraph->leafs[i];

        // Get buffer type name for leaf
        const char * leaf_buf_name = "none";
        ggml_backend_buffer_t leaf_buf = node->view_src ? node->view_src->buffer : node->buffer;
        if (leaf_buf) {
            leaf_buf_name = ggml_backend_buffer_name(leaf_buf);
        }

        file << " - " << std::setw(3) << i << ": [ "
             << std::setw(5) << node->ne[0] << ", "
             << std::setw(5) << node->ne[1] << "] "
             << std::setw(8) << ggml_op_name(node->op) << " "
             << std::setw(16) << ggml_get_name(node)
             << std::setw(20) << leaf_buf_name << "\n";
    }
    // clang-format on
    file << "========================================\n";

    file.close();
}

void print_tensor_address_map(const ggml_cgraph * cgraph) {
    std::map<void *, std::vector<std::string>> address_map;
    for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) {
        auto * node = cgraph->nodes[node_n];
        if (node->data) {
            auto it = address_map.find(node->data);
            if (it == address_map.end()) {
                address_map[node->data] = std::vector<std::string>();
            }
            address_map[node->data].push_back(node->name);
        }
    }
    for (const auto & pair : address_map) {
        std::cout << "Address: " << pair.first << '\n';
        for (const auto & name : pair.second) {
            std::cout << name << " ; ";
        }
        std::cout << "\n\n";
    }
}

ov::Shape GgmlOvDecoder::get_shape(const ggml_tensor * tensor) {
    std::vector<size_t> shape;
    for (int i = GGML_MAX_DIMS - 1; i >= 0; --i) {
        shape.push_back(static_cast<size_t>(tensor->ne[i]));
    }
    return shape;
}

std::vector<size_t> GgmlOvDecoder::get_stride(const ggml_tensor * tensor) {
    std::vector<size_t> stride;
    for (int i = GGML_MAX_DIMS - 1; i >= 0; --i) {
        stride.push_back(static_cast<size_t>(tensor->nb[i]));
    }
    return stride;
}

ov::element::Type GgmlOvDecoder::get_ov_type(const ggml_tensor * tensor) {
    switch (tensor->type) {
    case GGML_TYPE_F64:
        return ov::element::f64;
    case GGML_TYPE_F32:
        return ov::element::f32;
    case GGML_TYPE_F16:
        return ov::element::f16;
    case GGML_TYPE_BF16:
        return ov::element::bf16;
    case GGML_TYPE_I8:
        return ov::element::i8;
    case GGML_TYPE_I16:
        return ov::element::i16;
    case GGML_TYPE_I32:
        return ov::element::i32;
    case GGML_TYPE_I64:
        return ov::element::i64;
    default:
        return ov::element::dynamic;
    }
}

ov::PartialShape GgmlOvDecoder::get_input_shape(int node_idx, const std::string & name) const {
    return ov::PartialShape(get_shape(m_node_info_list[node_idx].node_inputs.at(name)));
}

std::vector<size_t> GgmlOvDecoder::get_input_stride(int node_idx, const std::string & name) const {
    return get_stride(m_node_info_list[node_idx].node_inputs.at(name));
}

size_t GgmlOvDecoder::get_view_input_size(int node_idx, const std::string & name) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        return it->second.size();
    }
    return 0;
}

size_t GgmlOvDecoder::get_view_input_offset(int node_idx, const std::string & name, size_t view_index) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        if (view_index < it->second.size()) {
            return it->second[view_index].second->view_offs;
        }
    }
    return 0;
}

size_t GgmlOvDecoder::get_view_input_src_offset(int node_idx, const std::string & name, size_t view_index) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        if (view_index < it->second.size()) {
            auto * view_tensor = it->second[view_index].second;
            if (view_tensor && view_tensor->src[0]) {
                return view_tensor->src[0]->view_offs;
            }
        }
    }
    return 0;
}

std::vector<size_t> GgmlOvDecoder::get_view_input_stride(int node_idx,
                                                         const std::string & name,
                                                         size_t view_index) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        if (view_index < it->second.size()) {
            return get_stride(it->second[view_index].second);
        }
    }
    return {};
}

std::vector<size_t> GgmlOvDecoder::get_view_input_src_stride(int node_idx,
                                                             const std::string & name,
                                                             size_t view_index) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        if (view_index < it->second.size()) {
            auto * view_tensor = it->second[view_index].second;
            if (view_tensor && view_tensor->src[0]) {
                return get_stride(view_tensor->src[0]);
            }
        }
    }
    return {};
}

ov::Shape GgmlOvDecoder::get_view_input_ggml_shape(int node_idx, const std::string & name, size_t view_index) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        if (view_index < it->second.size()) {
            return get_shape(it->second[view_index].second);
        }
    }
    return {};
}

ov::Shape GgmlOvDecoder::get_view_input_src_ggml_shape(int node_idx,
                                                       const std::string & name,
                                                       size_t view_index) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        if (view_index < it->second.size()) {
            auto * view_tensor = it->second[view_index].second;
            if (view_tensor && view_tensor->src[0]) {
                return get_shape(view_tensor->src[0]);
            }
        }
    }
    return {};
}

ov::PartialShape GgmlOvDecoder::get_view_input_ov_shape(int node_idx,
                                                        const std::string & name,
                                                        size_t view_index) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        if (view_index < it->second.size()) {
            auto * tensor = it->second[view_index].second;
            ov::PartialShape shape = ov::PartialShape{get_shape(tensor)};

            // Check if this tensor has a dynamic dimension
            auto dynamic_it = m_node_dynamic_dims.find(tensor);
            if (dynamic_it != m_node_dynamic_dims.end() && dynamic_it->second != -1) {
                int dynamic_dim_index = dynamic_it->second;
                // GGML uses reverse indexing, so convert to OpenVINO indexing
                shape[3 - dynamic_dim_index] = m_is_static ? get_static_n_tokens() : -1;
            }

            return shape;
        }
    }
    return {};
}

ov::PartialShape GgmlOvDecoder::get_view_input_src_ov_shape(int node_idx,
                                                            const std::string & name,
                                                            size_t view_index) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        if (view_index < it->second.size()) {
            auto * view_tensor = it->second[view_index].second;
            if (view_tensor && view_tensor->src[0]) {
                auto * src_tensor = view_tensor->src[0];
                ov::PartialShape shape = ov::PartialShape{get_shape(src_tensor)};

                // Check if this tensor has a dynamic dimension
                auto dynamic_it = m_node_dynamic_dims.find(src_tensor);
                if (dynamic_it != m_node_dynamic_dims.end() && dynamic_it->second != -1) {
                    int dynamic_dim_index = dynamic_it->second;
                    // GGML uses reverse indexing, so convert to OpenVINO indexing
                    shape[3 - dynamic_dim_index] = m_is_static ? get_static_n_tokens() : -1;
                }

                return shape;
            }
        }
    }
    return {};
}

std::string GgmlOvDecoder::get_view_input_name(int node_idx, const std::string & name, size_t view_index) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        if (view_index < it->second.size()) {
            return it->second[view_index].first;
        }
    }
    return "";
}

std::string GgmlOvDecoder::get_view_input_src_name(int node_idx, const std::string & name, size_t view_index) const {
    auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
    if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
        if (view_index < it->second.size()) {
            auto * view_tensor = it->second[view_index].second;
            if (view_tensor && view_tensor->src[0]) {
                return get_tensor_ov_name(m_cgraph, view_tensor->src[0]);
            }
        }
    }
    return "";
}

ov::element::Type GgmlOvDecoder::get_input_type(int node_idx, const std::string & name) const {
    return get_ov_type(m_node_info_list[node_idx].node_inputs.at(name));
}

size_t GgmlOvDecoder::get_input_size() const {
    return m_model_inputs.size();
}

size_t GgmlOvDecoder::get_input_size(int node_idx) const {
    return m_node_info_list[node_idx].node_inputs_names.size();
}

std::vector<std::string> GgmlOvDecoder::get_input_names(int node_idx) const {
    return m_node_info_list[node_idx].node_inputs_names;
}

ov::PartialShape GgmlOvDecoder::get_output_shape(int node_idx) const {
    auto * ggml_tensor = m_node_info_list[node_idx].node;
    return ov::PartialShape(get_shape(ggml_tensor));
}

ov::element::Type GgmlOvDecoder::get_output_type(const int node_idx) const {
    return get_ov_type(m_node_info_list[node_idx].node);
}

std::vector<size_t> GgmlOvDecoder::get_output_stride(int node_idx) const {
    auto * ggml_tensor = m_node_info_list[node_idx].node;
    return get_stride(ggml_tensor);
}

bool GgmlOvDecoder::is_direct_gdn_view(const ggml_tensor * node) const {
    if (node == nullptr || node->op != GGML_OP_VIEW || node->src[0] == nullptr ||
        node->src[0]->op != GGML_OP_GATED_DELTA_NET) {
        return false;
    }
    for (int i = 0; i < m_cgraph->n_nodes; ++i) {
        if (m_cgraph->nodes[i] == node->src[0]) {
            return get_output_names(i).size() > 1;
        }
    }
    return false;
}

std::vector<std::string> GgmlOvDecoder::get_output_names(int node_idx) const {
    auto * node = m_node_info_list[node_idx].node;
    if (is_ssm_state_writeback(node)) {
        // the written state block plus the full updated cache (see translate_cpy op_case 13)
        return {m_node_info_list[node_idx].node_name, get_tensor_ov_name(m_cgraph, node->view_src)};
    }
    if (node->op == GGML_OP_GATED_DELTA_NET && (!m_model_params.has_rs_rollback || node->op_params[0] > 1)) {
        std::string attn_name;
        std::string state_name;
        for (int i = node_idx + 1; i < m_cgraph->n_nodes; i++) {
            auto * consumer = m_cgraph->nodes[i];
            if (consumer->op != GGML_OP_VIEW || consumer->src[0] != node) {
                continue;
            }
            // GGML packs [attention | state]. The attention VIEW starts at offset 0 and the
            // state VIEW starts after the token-dependent attention segment.
            auto & name = consumer->view_offs == 0 ? attn_name : state_name;
            if (!name.empty()) {
                return {m_node_info_list[node_idx].node_name};
            }
            name = get_tensor_ov_name(m_cgraph, consumer);
        }
        if (!attn_name.empty() && !state_name.empty()) {
            if (m_model_params.has_rs_rollback) {
                return {m_node_info_list[node_idx].node_name, attn_name, state_name};
            }
            return {attn_name, state_name};
        }
    }
    return {m_node_info_list[node_idx].node_name};
}

std::string GgmlOvDecoder::get_inplace_op_src(int node_idx) const {
    auto * node = m_node_info_list[node_idx].node;
    if (is_ssm_state_writeback(node)) {
        // translate_cpy publishes the updated cache as a second named output
        return "";
    }
    // Reset lengths (also in static mode) and dynamic remainder views can become nonempty
    // after compilation. Keep their alias updates in the translated cache chain.
    const bool runtime_recurrent_write = !m_naive && is_recurrent_cache(node->view_src) &&
                                          (is_recurrent_cache_reset(node) || !m_is_static);
    if (!::is_inplace_op(node) || node->view_src == nullptr ||
        (ggml_nbytes(node) == 0 && !runtime_recurrent_write)) {
        return "";
    }
    const int op_case = m_node_info_list[node_idx].node_op_case;
    if (node->op == GGML_OP_CPY && (op_case == 1 || op_case == 2 || op_case == 3) &&
        m_compute_params.s_copy_active_slot_len == -1) {
        return "";
    }
    return get_tensor_ov_name(m_cgraph, node->view_src);
}

bool GgmlOvDecoder::is_view_like_alias_of(int node_idx, const std::string & view_src_name) const {
    auto * node = m_node_info_list[node_idx].node;
    if (node->view_src == nullptr || get_tensor_ov_name(m_cgraph, node->view_src) != view_src_name) {
        return false;
    }
    return node->op == GGML_OP_RESHAPE || node->op == GGML_OP_VIEW;
}

const std::string & GgmlOvDecoder::get_op_name() const {
    static const std::string unknown_name = "UNKNOWN_OP_NAME";
    return unknown_name;
}

int32_t GgmlOvDecoder::get_op_dynamic_dim(int node_idx) const {
    auto it = m_node_dynamic_dims.find(m_node_info_list[node_idx].node);
    if (it == m_node_dynamic_dims.end()) {
        return -1;
    }
    return it->second;
}

const std::string & GgmlOvDecoder::get_op_name(int node_idx) const {
    return m_node_info_list[node_idx].node_name;
}

int32_t * GgmlOvDecoder::get_input_op_params(int node_idx, const std::string & name) const {
    return m_node_info_list[node_idx].node_inputs.at(name)->op_params;
}

int32_t * GgmlOvDecoder::get_output_op_params(int node_idx) const {
    return m_node_info_list[node_idx].node->op_params;
}

size_t GgmlOvDecoder::get_output_op_offset(int node_idx) const {
    return m_node_info_list[node_idx].node->view_offs;
}

void GgmlOvDecoder::visit_subgraph(std::function<void(std::shared_ptr<GgmlDecoder>, int node_idx)> node_visitor) const {
    // One copy for the whole walk: translators only read the decoder, and a copy per node costs a full
    // copy of the node list for every node.
    auto decoder = std::make_shared<GgmlOvDecoder>(*this);
    for (int node_idx = 0; node_idx < m_cgraph->n_nodes; node_idx++) {
        if (m_cgraph->nodes[node_idx]->op == GGML_OP_NONE) {
            continue;
        }
        node_visitor(decoder, node_idx);
    }
}

std::string GgmlOvDecoder::compute_op_type(const ggml_tensor * node) {
    switch (node->op) {
    case GGML_OP_UNARY:
        return std::string("GGML_UNARY_OP_") + ggml_unary_op_name(ggml_get_unary_op(node));
    case GGML_OP_GLU:
        return std::string("GGML_GLU_OP_") + ggml_glu_op_name(ggml_get_glu_op(node));
    default:
        return std::string("GGML_OP_") + ggml_op_name(node->op);
    }
}

const std::string & GgmlOvDecoder::get_op_type(int node_idx) const {
    return m_node_info_list[node_idx].node_op_type;
}

const std::string & GgmlOvDecoder::get_op_type() const {
    static const std::string unknown_op = "UNKNOWN_GGML_OP";
    return unknown_op;
}

void GgmlOvDecoder::compute_node_dynamic_dims() {
    auto visit_node = [&](auto && self, ggml_tensor * node) -> void {
        if (!node) {
            return;
        }

        if (node->op == GGML_OP_CPY) {
            m_node_dynamic_dims[node] = -1;
        }

        if (m_node_dynamic_dims.count(node)) {
            return;
        }
        for (int i = 0; i < GGML_MAX_SRC; i++) {
            ggml_tensor * src = node->src[i];
            if (src == nullptr) {
                continue;
            }
            struct ggml_tensor * root_src = nullptr;
            // if (src->org_src) {
            //     root_src = src->org_src;
            // }
            if (root_src) {
                if (is_inp_tok(root_src, node) || is_inp_pos(root_src, node) || is_get_rows_input_idx(root_src, node)) {
                    m_node_dynamic_dims[root_src] = 0;
                    m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
                    continue;
                }
                self(self, root_src);
                m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
            } else {
                if (is_inp_tok(src, node) || is_inp_pos(src, node) || is_get_rows_input_idx(src, node)) {
                    m_node_dynamic_dims[src] = 0;
                    continue;
                }
                if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) {
                    m_node_dynamic_dims[src] = 1;
                    continue;
                }
                if (!m_is_static && is_activation_input(src, node)) {
                    m_node_dynamic_dims[src] = 1;
                    continue;
                }
                // a view of a model weight (BERT's token type row) has no token dim
                if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted &&
                    !(src->buffer != nullptr && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
                    m_node_dynamic_dims[src] = 1;
                    continue;
                }
                if (is_inp_embd_2d(src, node)) {
                    m_node_dynamic_dims[src] = 1;
                    continue;
                }
                self(self, src);
            }
        }
        switch (node->op) {
        case GGML_OP_NONE:
            m_node_dynamic_dims[node] = -1;
            break;
        case GGML_OP_GET_ROWS:
            m_node_dynamic_dims[node] = -1;
            if (m_node_dynamic_dims[node->src[1]] != -1) {
                auto dynamic_dim_idx = m_node_dynamic_dims[node->src[1]];
                if (dynamic_dim_idx == 0) {
                    m_node_dynamic_dims[node] = 1;
                } else if (dynamic_dim_idx == 2 && node->ne[3] == node->src[1]->ne[2]) {
                    // indices [k, ne11, ne12] -> result [ne00, k, ne11, ne12]
                    m_node_dynamic_dims[node] = 3;
                } else {
                    auto dynamic_dim_stride = node->src[1]->nb[dynamic_dim_idx] / ggml_type_size(node->src[1]->type) *
                                              ggml_type_size(node->src[0]->type);
                    for (int i = 0; i < GGML_MAX_DIMS; i++) {
                        if (dynamic_dim_stride == node->src[0]->nb[i]) {
                            m_node_dynamic_dims[node] = i;
                            break;
                        }
                    }
                }
                // OPENVINO_ASSERT(dynamic_dim_value == node->ne[m_node_dynamic_dims[node]],
                //                 "Dynamic dim value mismatch for node: " + std::string(node->name) +
                //                     " and its src[1]: " + std::string(node->src[1]->name));
            }
            break;
        case GGML_OP_MUL:
        case GGML_OP_MUL_MAT:
            m_node_dynamic_dims[node] = -1;
            if (m_node_dynamic_dims[node->src[0]] != -1) {
                m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
            }
            if (m_node_dynamic_dims[node->src[1]] != -1) {
                m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[1]];
            }
            break;
        case GGML_OP_PERMUTE:
            m_node_dynamic_dims[node] = -1;
            if (m_node_dynamic_dims[node->src[0]] != -1) {
                auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
                // auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
                // src dim i moves to dim op_params[i]
                if (dynamic_dim_idx >= 0 && dynamic_dim_idx < GGML_MAX_DIMS) {
                    m_node_dynamic_dims[node] = node->op_params[dynamic_dim_idx];
                }
                // OPENVINO_ASSERT(dynamic_dim_value == node->ne[m_node_dynamic_dims[node]],
                //                 "Dynamic dim value mismatch for node: " + std::string(node->name) +
                //                     " and its src[0]: " + std::string(node->src[0]->name));
            }
            break;
        case GGML_OP_VIEW: {
            if (is_sampling_view(node)) {
                m_node_dynamic_dims[node] = -1;
                break;
            }

            if (node->src[0]->op == GGML_OP_GATED_DELTA_NET && node->view_offs == 0) {
                m_node_dynamic_dims[node] = 2;
                break;
            }
            if (node->src[0]->op == GGML_OP_SSM_SCAN) {
                // y part [head_dim, n_head, n_tokens, n_seqs] at offset 0; the state part is token-independent
                m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1;
                break;
            }

            // A VIEW that does not change the shape is a pass-through for dynamic-dim purposes.
            if (is_same_shape(node->src[0], node)) {
                m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
                break;
            }
            // Use stride-based matching: the stride of a VIEW dimension directly
            // encodes which source dimension it indexes into, so it uniquely
            // identifies the dynamic dim even when two dims share the same size.
            m_node_dynamic_dims[node] = -1;
            if (!m_model_params.has_rs_rollback && node->src[0]->op == GGML_OP_GATED_DELTA_NET) {
                // The GDN translator publishes attention [S_v, H_v, n_tokens, n_seqs] and state directly under these
                // VIEW names (get_output_names), not the packed [attention | state] the strides describe.
                m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1;
                break;
            }
            if (m_node_dynamic_dims[node->src[0]] != -1) {
                auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
                auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
                auto dynamic_dim_stride =
                    node->src[0]->nb[dynamic_dim_idx] / ggml_type_size(node->src[0]->type) * ggml_type_size(node->type);
                if (node->src[0]->op == GGML_OP_NONE) {
                    // A view of a KV cache covers fewer cells than the cache holds, so only the stride identifies the
                    // dim: [n_embd, kv_size] viewed as [head_dim, n_head_kv, n_kv] moves the cells from dim 1 to 2.
                    m_node_dynamic_dims[node] = dynamic_dim_idx;
                    for (int i = 0; i < GGML_MAX_DIMS; i++) {
                        if (node->nb[i] == dynamic_dim_stride && node->ne[i] != 1) {
                            m_node_dynamic_dims[node] = i;
                            break;
                        }
                    }
                    break;
                }
                // A size-1 dim may carry any stride (MLA's k_pe = ggml_view_3d(.., ne1 = 1, ..) gives it the row
                // stride), so among the dims with the source's stride take the outermost one of the same size.
                // With a dynamic size of 1 every trailing size-1 dim matches (Qwen3.5's Qcur view: ne2 = n_tokens = 1,
                // nb3 == nb2), so keep the innermost match there.
                for (int i = 0; i < GGML_MAX_DIMS; i++) {
                    const bool first_match = m_node_dynamic_dims[node] == -1;
                    const bool same_size = dynamic_dim_value != 1 && node->ne[i] == dynamic_dim_value;
                    if (node->nb[i] == dynamic_dim_stride && (first_match || same_size)) {
                        m_node_dynamic_dims[node] = i;
                    }
                }
                if (m_node_dynamic_dims[node] != -1 && dynamic_dim_value != node->ne[m_node_dynamic_dims[node]]) {
                    m_node_dynamic_dims[node] = -1;
                    // an empty view, e.g. the extra states of a single-slot recurrent cache, always mismatches
                    if (ggml_nelements(node) > 0) {
                        GGML_LOG_WARN("ggml-openvino: dynamic dim value mismatch for VIEW node '%s', src[0]: '%s'\n",
                                      node->name, node->src[0]->name);
                    }
                }
            }
            break;
        }
        case GGML_OP_TRANSPOSE:
        case GGML_OP_RESHAPE: {
            if (is_same_shape(node->src[0], node)) {
                m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
                break;
            }
            // RESHAPE requires src[0] to be contiguous, so both src and result
            // have standard compact strides: nb[i] = type_size * prod(ne[0..i-1]).
            // Match src->nb[dynamic_dim] against result->nb[i] to find the output
            // dimension whose flat-memory boundary aligns with the source dynamic
            // boundary. This handles merged-lower-dim cases that ne-value matching
            // misses. A size-1 dim has the same stride as the dim after it
            // ([head_dim, T] -> [head_dim, 1, T] with one KV head), so prefer the
            // matching dim that also has the source dim's size.
            m_node_dynamic_dims[node] = -1;
            if (m_node_dynamic_dims[node->src[0]] != -1) {
                auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
                auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
                auto dynamic_dim_stride = node->src[0]->nb[dynamic_dim_idx];
                for (int i = 0; i < GGML_MAX_DIMS; i++) {
                    if (node->nb[i] != dynamic_dim_stride) {
                        continue;
                    }
                    if (m_node_dynamic_dims[node] == -1) {
                        m_node_dynamic_dims[node] = i;
                    }
                    if (node->ne[i] == dynamic_dim_value) {
                        m_node_dynamic_dims[node] = i;
                        break;
                    }
                }
                if (m_node_dynamic_dims[node] == -1) {
                    GGML_LOG_WARN("ggml-openvino: cannot determine dynamic dim for RESHAPE node '%s'\n", node->name);
                }
            }
            break;
        }
        case GGML_OP_FLASH_ATTN_EXT: {
            // Output shape is hard-coded in ggml_flash_attn_ext as:
            //   ne = { v->ne[0], q->ne[2], q->ne[1], q->ne[3] }
            // i.e. output dim 0 <- v dim 0 (head_size, static)
            //      output dim 1 <- q dim 2 (n_heads,   static)
            //      output dim 2 <- q dim 1 (n_tokens,  potentially dynamic)
            //      output dim 3 <- q dim 3 (batch,     static)
            // Using the fixed q-dim -> output-dim mapping table.
            // q is src[0]; the mapping from q's dynamic dim to the output dim is:
            //   q dim 1 -> output dim 2
            //   q dim 2 -> output dim 1
            //   q dim 3 -> output dim 3
            //   q dim 0 -> output dim 0  (head_size axis, unlikely to be dynamic)
            constexpr int q_to_out[GGML_MAX_DIMS] = {0, 2, 1, 3};
            m_node_dynamic_dims[node] = -1;
            if (m_node_dynamic_dims[node->src[0]] != -1) {
                auto q_dynamic_dim = m_node_dynamic_dims[node->src[0]];
                m_node_dynamic_dims[node] = q_to_out[q_dynamic_dim];
            }
            break;
        }
        case GGML_OP_CONT:
            m_node_dynamic_dims[node] = -1;
            if (m_node_dynamic_dims[node->src[0]] != -1) {
                auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
                if (ggml_are_same_shape(node, node->src[0])) {
                    m_node_dynamic_dims[node] = dynamic_dim_idx;
                } else {
                    size_t src_logical_nb[GGML_MAX_DIMS];
                    src_logical_nb[0] = ggml_type_size(node->src[0]->type);
                    src_logical_nb[1] = src_logical_nb[0] * (node->src[0]->ne[0] / ggml_blck_size(node->src[0]->type));
                    for (int i = 2; i < GGML_MAX_DIMS; i++) {
                        src_logical_nb[i] = src_logical_nb[i - 1] * node->src[0]->ne[i - 1];
                    }

                    auto dynamic_dim_stride = src_logical_nb[dynamic_dim_idx] / ggml_type_size(node->src[0]->type) *
                                              ggml_type_size(node->type);
                    int matched_dim_count = 0;
                    int first_matched_dim = -1;
                    for (int i = 0; i < GGML_MAX_DIMS; i++) {
                        if (node->nb[i] == dynamic_dim_stride && node->ne[i] == node->src[0]->ne[dynamic_dim_idx]) {
                            if (first_matched_dim == -1) {
                                first_matched_dim = i;
                            }
                            m_node_dynamic_dims[node] = i;
                            matched_dim_count++;
                        }
                    }
                    if (matched_dim_count > 1 && node->src[0]->ne[dynamic_dim_idx] == 1) {
                        // Single-token capture: every trailing dim is size 1 with the same stride, so
                        // the match is ambiguous. The lowest index is the real axis; the rest are
                        // ggml's size-1 padding. Bailing out here would bake the captured token count
                        // into the static prefill model, which then runs with a different one.
                        m_node_dynamic_dims[node] = first_matched_dim;
                    } else if (matched_dim_count != 1) {
                        m_node_dynamic_dims[node] = -1;
                        GGML_LOG_WARN("ggml-openvino: cannot determine dynamic dim for CONT node '%s', src[0]: '%s'\n",
                                      node->name, node->src[0]->name);
                    }
                }
            }
            break;
        case GGML_OP_CONCAT: {
            const int axis = node->op_params[0];
            const int src0_dynamic_dim = m_node_dynamic_dims[node->src[0]];
            const int src1_dynamic_dim = m_node_dynamic_dims[node->src[1]];
            if (src0_dynamic_dim != -1 && src0_dynamic_dim != axis &&
                src1_dynamic_dim != -1 && src1_dynamic_dim != axis && src0_dynamic_dim != src1_dynamic_dim) {
                GGML_LOG_WARN("ggml-openvino: different dynamic dims for CONCAT node '%s', src[0]: '%s', src[1]: '%s'\n",
                              node->name, node->src[0]->name, node->src[1]->name);
            }
            m_node_dynamic_dims[node] = axis;
            for (int i = 0; i < 2; ++i) {
                const int dynamic_axis = m_node_dynamic_dims[node->src[i]];
                if (dynamic_axis != -1 && dynamic_axis != axis) {
                    m_node_dynamic_dims[node] = dynamic_axis;
                    break;
                }
            }
            break;
        }
        case GGML_OP_SSM_CONV:
        case GGML_OP_GATED_DELTA_NET:
            m_node_dynamic_dims[node] = 1;
            break;
        case GGML_OP_SSM_SCAN:
            // packed 1-D [y | state]; the y part grows with tokens
            m_node_dynamic_dims[node] = 0;
            break;
        case GGML_OP_RMS_NORM:
        case GGML_OP_L2_NORM:
        case GGML_OP_NORM:
        case GGML_OP_ADD:
        case GGML_OP_SUB:
        case GGML_OP_GLU:
        case GGML_OP_ROPE:
        case GGML_OP_SCALE:
        case GGML_OP_SOFT_MAX:
        case GGML_OP_ARGSORT:
        case GGML_OP_TOP_K:
        case GGML_OP_ADD_ID:
        case GGML_OP_UNARY:
        case GGML_OP_CUMSUM:
        case GGML_OP_FILL:
        case GGML_OP_SET:
        case GGML_OP_DIAG:
        case GGML_OP_TRI:
        case GGML_OP_REPEAT:
        case GGML_OP_DUP:
        // Shape-preserving elementwise ops: the dynamic dim is unchanged from src[0].
        // DIV/CLAMP are used in the MoE routing-weight normalization
        // (sum_rows -> clamp -> div). If they are left untracked here the dynamic
        // (token) dim is lost there, the captured prefill token count gets baked into
        // the downstream reshapes, and every decoder layer after layer 0 turns static
        // (which then triggers the GPU in-place-concat KV-cache corruption).
        case GGML_OP_DIV:
        case GGML_OP_CLAMP:
        case GGML_OP_PAD:
        case GGML_OP_UPSCALE:
        case GGML_OP_SIN:
        case GGML_OP_COS:
        case GGML_OP_LOG:
        case GGML_OP_ROLL:
            m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
            break;
        case GGML_OP_SUM_ROWS:
        case GGML_OP_POOL_1D:
            // SUM_ROWS/POOL_1D change only ggml axis 0 and preserve all other axes, so the
            // dynamic dim is preserved unless it was axis 0.
            m_node_dynamic_dims[node] =
                (m_node_dynamic_dims[node->src[0]] == 0) ? -1 : m_node_dynamic_dims[node->src[0]];
            break;
        case GGML_OP_MUL_MAT_ID:
        case GGML_OP_SOLVE_TRI:
            m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[1]];
            break;
        case GGML_OP_CPY:
        case GGML_OP_SUM:
        case GGML_OP_MEAN:
        case GGML_OP_ARANGE:
            m_node_dynamic_dims[node] = -1;
            break;
        case GGML_OP_SET_ROWS:
            // a cache or column write returns its whole buffer; other rows writes keep the shape of their destination
            m_node_dynamic_dims[node] =
                (is_kvcache_write(node) || is_conv_state_snapshot_writeback(node) || is_column_set_rows(node)) ?
                    -1 :
                    m_node_dynamic_dims[node->src[2]];
            break;
        case GGML_OP_IM2COL: {
            m_node_dynamic_dims[node] = -1;
            if (m_node_dynamic_dims[node->src[1]] != -1) {
                const bool is_2D = node->op_params[6] == 1;
                const int src_dyn = m_node_dynamic_dims[node->src[1]];
                if (is_2D) {
                    if (src_dyn == 0) {
                        m_node_dynamic_dims[node] = 1;  // IW -> OW
                    } else if (src_dyn == 1) {
                        m_node_dynamic_dims[node] = 2;  // IH -> OH
                    } else if (src_dyn == 3) {
                        m_node_dynamic_dims[node] = 3;  // N  -> N
                    }
                } else {
                    if (src_dyn == 0) {
                        m_node_dynamic_dims[node] = 1;  // IW -> OW
                    } else if (src_dyn == 2) {
                        m_node_dynamic_dims[node] = 2;  // N  -> N  (1D: b->ne[2] is the batch/channel dim)
                    }
                }
                if (m_node_dynamic_dims[node] != -1) {
                    OPENVINO_ASSERT(node->src[1]->ne[src_dyn] == node->ne[m_node_dynamic_dims[node]],
                                    "Dynamic dim value mismatch for IM2COL node: " + std::string(node->name) +
                                        " and its src[1]: " + std::string(node->src[1]->name));
                }
            }
            break;
        }
        case GGML_OP_IM2COL_3D: {
            m_node_dynamic_dims[node] = -1;
            if (m_node_dynamic_dims[node->src[1]] != -1) {
                const int src_dyn = m_node_dynamic_dims[node->src[1]];
                if (src_dyn == 0) {
                    m_node_dynamic_dims[node] = 1;  // IW -> OW
                } else if (src_dyn == 1) {
                    m_node_dynamic_dims[node] = 2;  // IH -> OH
                } else if (src_dyn == 3) {
                    m_node_dynamic_dims[node] = 3;  // N  -> N
                }
                if (m_node_dynamic_dims[node] != -1) {
                    OPENVINO_ASSERT(node->src[1]->ne[src_dyn] == node->ne[m_node_dynamic_dims[node]],
                                    "Dynamic dim value mismatch for IM2COL_3D node: " + std::string(node->name) +
                                        " and its src[1]: " + std::string(node->src[1]->name));
                }
            }
            break;
        }
        default:
            GGML_LOG_DEBUG("ggml-openvino: compute_node_dynamic_dims: unhandled op %s for node '%s'\n",
                           ggml_op_name(node->op), node->name);
            break;
        }
    };

    for (int i = 0; i < m_cgraph->n_nodes; i++) {
        ggml_tensor * node = m_cgraph->nodes[i];
        visit_node(visit_node, node);
    }

    // print the nodes in m_cgraph name & shape with the dynamic dim (the dynamic dim is the dimension with -1 in m_node_dynamic_dims) for debugging
    if (0) {
        for (int i = 0; i < m_cgraph->n_nodes; i++) {
            ggml_tensor * node = m_cgraph->nodes[i];
            int dynamic_dim = m_node_dynamic_dims[node];
            std::cout << "[" << i << "] " << "node_name: " << node->name << " op: " << ggml_op_name(node->op)
                      << " shape: [";
            for (int j = 0; j < 4; j++) {
                if (j == dynamic_dim) {
                    std::cout << "*";
                } else {
                    std::cout << node->ne[j];
                }
                if (j < 3) {
                    std::cout << ", ";
                }
            }
            std::cout << "]" << '\n';
            // print the src name & shape with the dynamic dim for debugging
            for (int j = 0; j < GGML_MAX_SRC; j++) {
                ggml_tensor * src = node->src[j];
                if (src == nullptr) {
                    continue;
                }
                int src_dynamic_dim = m_node_dynamic_dims[src];
                std::cout << "    [" << j << "] src_name: " << src->name << " [";
                for (int k = 0; k < 4; k++) {
                    if (k == src_dynamic_dim) {
                        std::cout << "*";
                    } else {
                        std::cout << src->ne[k];
                    }
                    if (k < 3) {
                        std::cout << ", ";
                    }
                }
                std::cout << "]" << '\n';
            }
            std::cout << '\n';
        }
    }
}