transcribe-cpp-sys 0.5.2

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
#include "gated_delta_net.hpp"

#include "../node_context.h"
#include "../op_table.h"
#include "../utils.h"
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
#include "recurrent_cache_update.hpp"
#endif
#include "ggml-openvino/ggml-openvino-extra.h"

#include <cmath>
#include <cstdint>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <openvino/core/model.hpp>
#include <openvino/op/add.hpp>
#include <openvino/op/broadcast.hpp>
#include <openvino/op/concat.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/convert.hpp>
#include <openvino/op/divide.hpp>
#include <openvino/op/exp.hpp>
#include <openvino/op/gather.hpp>
#include <openvino/op/less.hpp>
#include <openvino/op/loop.hpp>
#include <openvino/op/matmul.hpp>
#include <openvino/op/maximum.hpp>
#include <openvino/op/minimum.hpp>
#include <openvino/op/multiply.hpp>
#include <openvino/op/parameter.hpp>
#include <openvino/op/range.hpp>
#include <openvino/op/reduce_mean.hpp>
#include <openvino/op/reshape.hpp>
#include <openvino/op/select.hpp>
#include <openvino/op/shape_of.hpp>
#include <openvino/op/slice.hpp>
#include <openvino/op/split.hpp>
#include <openvino/op/sqrt.hpp>
#include <openvino/op/squeeze.hpp>
#include <openvino/op/subtract.hpp>
#include <openvino/op/tile.hpp>
#include <openvino/op/transpose.hpp>
#include <openvino/op/unsqueeze.hpp>
#include <utility>
#include <vector>

namespace ov {
namespace frontend {
namespace ggml {
namespace op {

static OutputVector translate_gated_delta_net_ref(const NodeContext & context);

// Asks the device: OpenVINO releases without the per-key gate reject a rank-4 gate when the node is built, and a plugin
// without a per-key kernel leaves the node out of query_model
bool gdn_per_key_gate_supported() {
    static const bool supported = [] {
        ov::ParameterVector params;
        auto param = [&params](const ov::Shape & shape) {
            params.push_back(std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape));
            return params.back();
        };
        std::shared_ptr<ov::Node> gdn;
        try {
            gdn = std::make_shared<ov::op::internal::GatedDeltaNet>(param({1, 1, 1, 2}), param({1, 1, 1, 2}),
                                                                    param({1, 1, 1, 2}), param({1, 1, 2, 2}),
                                                                    param({1, 1, 1, 2}), param({1, 1, 1}));
        } catch (const ov::Exception &) {
            return false;
        }
        const auto model = std::make_shared<ov::Model>(gdn->outputs(), params);
        return ov_singleton_core()
                   .query_model(model, ggml_openvino_get_device_name())
                   .count(gdn->get_friendly_name()) != 0;
    }();
    return supported;
}

static bool match_gdn_l2_norm(const Output<Node> & normalized, Output<Node> & input, float & eps) {
    // Match the RMSNorm decomposition emitted by translate_rms_norm, followed by GGML SCALE.
    const auto scale = ov::as_type_ptr<ov::op::v1::Multiply>(normalized.get_node_shared_ptr());
    if (!scale) {
        return false;
    }
    const auto factor = ov::as_type_ptr<ov::op::v0::Constant>(scale->get_input_node_shared_ptr(1));
    const auto rms = ov::as_type_ptr<ov::op::v1::Multiply>(scale->get_input_node_shared_ptr(0));
    if (!factor || ov::shape_size(factor->get_shape()) != 1 || !rms) {
        return false;
    }
    const auto x = rms->input_value(0);
    const auto & shape = x.get_partial_shape();
    if (x.get_element_type() != ov::element::f32 || shape.rank() != 4 || shape[3].is_dynamic() ||
        shape[3].get_length() <= 0 || normalized.get_partial_shape() != shape) {
        return false;
    }
    const float dim = static_cast<float>(shape[3].get_length());
    if (factor->cast_vector<float>()[0] != 1.0f / std::sqrt(dim)) {
        return false;
    }
    const auto reciprocal = ov::as_type_ptr<ov::op::v1::Divide>(rms->get_input_node_shared_ptr(1));
    if (!reciprocal) {
        return false;
    }
    const auto one = ov::as_type_ptr<ov::op::v0::Constant>(reciprocal->get_input_node_shared_ptr(0));
    const auto root = ov::as_type_ptr<ov::op::v0::Sqrt>(reciprocal->get_input_node_shared_ptr(1));
    if (!one || ov::shape_size(one->get_shape()) != 1 || one->cast_vector<float>()[0] != 1.0f || !root) {
        return false;
    }
    const auto add = ov::as_type_ptr<ov::op::v1::Add>(root->get_input_node_shared_ptr(0));
    if (!add) {
        return false;
    }
    const auto mean = ov::as_type_ptr<ov::op::v1::ReduceMean>(add->get_input_node_shared_ptr(0));
    const auto rms_eps = ov::as_type_ptr<ov::op::v0::Constant>(add->get_input_node_shared_ptr(1));
    if (!mean || !mean->get_keep_dims() || !rms_eps || ov::shape_size(rms_eps->get_shape()) != 1) {
        return false;
    }
    const auto axes = ov::as_type_ptr<ov::op::v0::Constant>(mean->get_input_node_shared_ptr(1));
    const auto square = ov::as_type_ptr<ov::op::v1::Multiply>(mean->get_input_node_shared_ptr(0));
    if (!axes || axes->cast_vector<int64_t>() != std::vector<int64_t>{-1} || !square ||
        square->input_value(0) != x || square->input_value(1) != x) {
        return false;
    }
    // RMSNorm(x, rms_eps) / sqrt(D) = x / sqrt(sum(x*x) + D*rms_eps).
    eps = dim * rms_eps->cast_vector<float>()[0];
    if (!std::isfinite(eps) || eps <= 0.0f) {
        return false;
    }
    input = x;
    return true;
}

// A [CS, CS] mask of the chunked GatedDeltaNet, one instance per content for the whole process. The NPUW weights
// bank, which all compiled models share (NPUW_WEIGHTS_BANK=shared), identifies a constant by its data pointer and
// keeps its tensor after the model that owned it is gone. A mask of a later model that got the address of a freed
// mask would then be read as that other mask, so a mask is never freed. Not needed once NPUW stops matching a new
// constant to a detached one by pointer (OpenVINO 2026.4 does).
static std::shared_ptr<ov::op::v0::Constant> gdn_chunk_mask(int64_t CS, const std::vector<float> & values) {
    static std::mutex mutex;
    static std::map<std::vector<float>, std::shared_ptr<ov::op::v0::Constant>> cache;
    std::lock_guard<std::mutex> lock(mutex);
    auto & mask = cache[values];
    if (!mask) {
        mask = ov::op::v0::Constant::create(ov::element::f32, {(size_t) CS, (size_t) CS}, values);
    }
    return mask;
}

// Chunked GatedDeltaNet built from MatMuls, for devices where the GatedDeltaNet op cannot run (NPU4000).
// Same contract as the op with equal q/k/v heads and no fused l2 norm:
//   q, k [B, T, H, Dk], v [B, T, H, Dv], g, beta [B, T, H], state [B, H, Dk, Dv]
//   returns attn [B, T, H, Dv] and the new state [B, H, Dk, Dv].
// Per chunk of CS tokens (gc = cumsum of g in the chunk, decay[i][j] = exp(gc_i - gc_j) for j <= i, else 0):
//   P    = (I + strict_lower(beta k k^T * decay))^-1
//   u    = P (beta v),  w = P (beta k exp(gc))
//   v'   = u - w S
//   out  = (q exp(gc)) S + lower(q k^T * decay) v'
//   S    = S exp(gc_last) + (k exp(gc_last - gc))^T v'
// The chunks run one after another; everything inside a chunk is batched over all chunks and heads.
// P is built block-recursively, [[A, 0], [C, D]]^-1 = [[A^-1, 0], [-D^-1 C A^-1, D^-1]], for block sizes
// 1, 2, 4, ..., CS / 2. Every intermediate is a part of the true inverse, so values stay small in f16. A Neumann
// product (I - L)(I + L^2)... is exact too, but powers of L grow large and cancel, which f16 cannot hold.
// A single token (decode) is a chunk of one token, where P = 1 and decay = 1:
//   v'   = beta (v - exp(g) k S)
//   S    = S exp(g) + k^T v'
//   out  = q S
// No Loop op is used, so the GatedDeltaNet loop fusion does not turn this back into the op.
static std::pair<Output<Node>, Output<Node>> make_gated_delta_net_chunked(Output<Node> q, Output<Node> k,
                                                                          Output<Node> v, Output<Node> g,
                                                                          Output<Node> beta, Output<Node> state,
                                                                          int64_t B, int64_t T, int64_t H, int64_t Dk,
                                                                          int64_t Dv) {
    const int64_t CS = ggml_openvino_gdn_decompose_chunk();
    const int64_t max_dim = std::numeric_limits<int64_t>::max();
    FRONT_END_OP_CONVERSION_CHECK(B > 0 && T > 0 && H > 0 && Dk > 0 && Dv > 0,
                                  "GATED_DELTA_NET decomposition requires positive dimensions");
    const int64_t pad = (CS - T % CS) % CS;
    FRONT_END_OP_CONVERSION_CHECK(T <= max_dim - pad && B <= max_dim / H,
                                  "GATED_DELTA_NET decomposition dimensions overflow");
    const int64_t N = (T + pad) / CS;
    const int64_t X = B * H;
    FRONT_END_OP_CONVERSION_CHECK(X <= max_dim / N / CS / CS && X <= max_dim / N / CS / Dk &&
                                  X <= max_dim / N / CS / Dv && X <= max_dim / Dk / Dv,
                                  "GATED_DELTA_NET decomposition tensor size overflows");

    auto i64 = [](const std::vector<int64_t> & v) {
        return ov::op::v0::Constant::create(ov::element::i64, {v.size()}, v);
    };
    auto f32 = [](float x) { return ov::op::v0::Constant::create(ov::element::f32, {}, {x}); };
    auto reshape = [&](const Output<Node> & x, const std::vector<int64_t> & shape) -> Output<Node> {
        return std::make_shared<ov::op::v1::Reshape>(x, i64(shape), false);
    };
    auto transpose = [&](const Output<Node> & x, const std::vector<int64_t> & perm) -> Output<Node> {
        return std::make_shared<ov::op::v1::Transpose>(x, i64(perm));
    };
    auto matmul = [](const Output<Node> & a, const Output<Node> & b, bool ta = false, bool tb = false) -> Output<Node> {
        return std::make_shared<ov::op::v0::MatMul>(a, b, ta, tb);
    };
    auto mul = [](const Output<Node> & a, const Output<Node> & b) -> Output<Node> {
        return std::make_shared<ov::op::v1::Multiply>(a, b);
    };
    auto add = [](const Output<Node> & a, const Output<Node> & b) -> Output<Node> {
        return std::make_shared<ov::op::v1::Add>(a, b);
    };
    auto sub = [](const Output<Node> & a, const Output<Node> & b) -> Output<Node> {
        return std::make_shared<ov::op::v1::Subtract>(a, b);
    };
    auto exp_op = [](const Output<Node> & x) -> Output<Node> { return std::make_shared<ov::op::v0::Exp>(x); };

    if (T == 1) {
        // [B, 1, H, D] -> [1, X, 1, D], batch 1 as below
        q = mul(reshape(q, {1, X, 1, Dk}), f32(1.0f / std::sqrt((float) Dk)));
        k = reshape(k, {1, X, 1, Dk});
        v = reshape(v, {1, X, 1, Dv});
        auto state_decay = exp_op(reshape(g, {1, X, 1, 1}));
        beta = reshape(beta, {1, X, 1, 1});
        Output<Node> s = reshape(state, {1, X, Dk, Dv});
        auto v_new = mul(sub(v, matmul(mul(k, state_decay), s)), beta);  // [1, X, 1, Dv]
        s = add(mul(s, state_decay), matmul(k, v_new, true, false));     // [1, X, Dk, Dv]
        return {reshape(matmul(q, s), {B, 1, H, Dv}), reshape(s, {B, H, Dk, Dv})};
    }

    // Pad T to a multiple of CS. A padded token has g = 0 and beta = k = 0, so it leaves the state unchanged.
    if (pad > 0) {
        auto pad_tokens = [&](const Output<Node> & x, std::vector<size_t> zero_shape) -> Output<Node> {
            zero_shape[1] = pad;
            auto zeros = ov::op::v0::Constant::create(ov::element::f32, zero_shape, std::vector<float>{0.0f});
            return std::make_shared<ov::op::v0::Concat>(ov::OutputVector{x, zeros}, 1);
        };
        q = pad_tokens(q, {(size_t) B, 0, (size_t) H, (size_t) Dk});
        k = pad_tokens(k, {(size_t) B, 0, (size_t) H, (size_t) Dk});
        v = pad_tokens(v, {(size_t) B, 0, (size_t) H, (size_t) Dv});
        g = pad_tokens(g, {(size_t) B, 0, (size_t) H});
        beta = pad_tokens(beta, {(size_t) B, 0, (size_t) H});
    }

    // Batch stays 1 for the NPU (a batched eltwise is split per batch and mis-broadcasts): X = B * H.
    // [B, T, H, D] -> [1, X * N, CS, D]
    auto to_chunks = [&](const Output<Node> & x, int64_t d) {
        return reshape(transpose(x, {0, 2, 1, 3}), {1, X * N, CS, d});
    };
    q = mul(to_chunks(q, Dk), f32(1.0f / std::sqrt((float) Dk)));
    k = to_chunks(k, Dk);
    v = to_chunks(v, Dv);
    g = reshape(transpose(g, {0, 2, 1}), {1, X * N, CS, 1});
    beta = reshape(transpose(beta, {0, 2, 1}), {1, X * N, CS, 1});

    std::vector<float> lower_incl(CS * CS), lower_strict(CS * CS), identity(CS * CS);
    for (int64_t i = 0; i < CS; i++) {
        for (int64_t j = 0; j < CS; j++) {
            lower_incl[i * CS + j] = j <= i ? 1.0f : 0.0f;
            lower_strict[i * CS + j] = j < i ? 1.0f : 0.0f;
            identity[i * CS + j] = i == j ? 1.0f : 0.0f;
        }
    }
    auto lower_incl_mask = gdn_chunk_mask(CS, lower_incl);
    auto lower_strict_mask = gdn_chunk_mask(CS, lower_strict);
    auto eye = gdn_chunk_mask(CS, identity);

    // cumsum of g inside a chunk as a MatMul with the lower triangle of ones: gc [1, X * N, CS, 1]
    auto gc_col = matmul(lower_incl_mask, g);
    auto gc_row = reshape(gc_col, {1, X * N, 1, CS});
    auto causal = std::make_shared<ov::op::v0::Convert>(lower_incl_mask, ov::element::boolean);
    auto log_decay = std::make_shared<ov::op::v1::Select>(causal, sub(gc_col, gc_row), f32(0.0f));
    auto decay = mul(exp_op(log_decay), lower_incl_mask);

    auto kb = mul(k, beta);
    auto vb = mul(v, beta);

    // P = (I + L)^-1 with L = strict_lower(beta k k^T * decay)
    auto neg_l = mul(mul(mul(matmul(kb, k, false, true), decay), lower_strict_mask), f32(-1.0f));
    // p holds the inverses of the diagonal b x b blocks; merging pairs of them only needs the -L entries
    // in the lower off-diagonal b x b block of each 2b x 2b block: p += p (-L masked) p
    auto block_mask = [&](int64_t b) {
        std::vector<float> m(CS * CS);
        for (int64_t i = 0; i < CS; i++) {
            for (int64_t j = 0; j < CS; j++) {
                m[i * CS + j] = (i / (2 * b) == j / (2 * b) && i / b > j / b) ? 1.0f : 0.0f;
            }
        }
        return gdn_chunk_mask(CS, m);
    };
    Output<Node> p = add(eye, mul(neg_l, block_mask(1)));
    for (int64_t b = 2; b < CS; b *= 2) {
        p = add(p, matmul(matmul(p, mul(neg_l, block_mask(b))), p));
    }

    auto gc_exp = exp_op(gc_col);                     // [1, X * N, CS, 1]
    auto u = matmul(p, vb);                           // [1, X * N, CS, Dv]
    auto w = matmul(p, mul(kb, gc_exp));              // [1, X * N, CS, Dk]
    auto qg = mul(q, gc_exp);                         // [1, X * N, CS, Dk]
    auto qk = mul(matmul(q, k, false, true), decay);  // [1, X * N, CS, CS]
    auto gc_last = std::make_shared<ov::op::v8::Slice>(gc_col, i64({CS - 1}), i64({CS}), i64({1}), i64({2}));
    auto kg = mul(k, exp_op(sub(gc_last, gc_col)));   // [1, X * N, CS, Dk]
    auto state_decay = exp_op(gc_last);               // [1, X * N, 1, 1]

    // Per-chunk slices, reshaped to [X, rows, cols]
    auto chunk_axis = ov::op::v0::Constant::create(ov::element::i64, {}, {1});
    auto split_chunks = [&](const Output<Node> & x, int64_t rows, int64_t cols) {
        auto split = std::make_shared<ov::op::v1::Split>(reshape(x, {X, N, rows * cols}), chunk_axis,
                                                         static_cast<size_t>(N));
        std::vector<Output<Node>> parts;
        for (int64_t n = 0; n < N; n++) {
            parts.push_back(reshape(split->output(n), {X, rows, cols}));
        }
        return parts;
    };
    auto u_n = split_chunks(u, CS, Dv);
    auto w_n = split_chunks(w, CS, Dk);
    auto qg_n = split_chunks(qg, CS, Dk);
    auto qk_n = split_chunks(qk, CS, CS);
    auto kg_n = split_chunks(kg, CS, Dk);
    auto state_decay_n = split_chunks(state_decay, 1, 1);

    Output<Node> s = reshape(state, {X, Dk, Dv});
    ov::OutputVector outs;
    for (int64_t n = 0; n < N; n++) {
        auto v_new = sub(u_n[n], matmul(w_n[n], s));                             // [X, CS, Dv]
        outs.push_back(add(matmul(qg_n[n], s), matmul(qk_n[n], v_new)));         // [X, CS, Dv]
        s = add(mul(s, state_decay_n[n]), matmul(kg_n[n], v_new, true, false));  // [X, Dk, Dv]
    }

    Output<Node> attn = N > 1 ? std::make_shared<ov::op::v0::Concat>(outs, 1)->output(0) : outs[0];
    if (pad > 0) {
        attn = std::make_shared<ov::op::v8::Slice>(attn, i64({0}), i64({T}), i64({1}), i64({1}));
    }
    attn = reshape(attn, {B, H, T, Dv});
    return {transpose(attn, {0, 2, 1, 3}), reshape(s, {B, H, Dk, Dv})};
}

static OutputVector make_gated_delta_net(const Output<Node> & q,
                                        const Output<Node> & k,
                                        const Output<Node> & v,
                                        const Output<Node> & state,
                                        const Output<Node> & g,
                                        const Output<Node> & beta,
                                        bool norm,
                                        float q_eps,
                                        float k_eps) {
    const auto & q_shape = q.get_partial_shape();
    const auto & v_shape = v.get_partial_shape();
    if (ggml_openvino_gdn_decompose_enabled() && !norm && q_shape.is_static() && v_shape.is_static()) {
        auto outputs = make_gated_delta_net_chunked(q, k, v, g, beta, state,
                                                   q_shape[0].get_length(), q_shape[1].get_length(),
                                                   v_shape[2].get_length(), q_shape[3].get_length(),
                                                   v_shape[3].get_length());
        return {outputs.first, outputs.second};
    }
    auto gdn = std::make_shared<ov::op::internal::GatedDeltaNet>(q, k, v, state, g, beta, norm, q_eps, k_eps);
    return {gdn->output(0), gdn->output(1)};
}

static OutputVector translate_gdn_snapshots(const Output<Node> & q,
                                          const Output<Node> & k,
                                          const Output<Node> & v,
                                          const Output<Node> & state,
                                          const Output<Node> & g,
                                          const Output<Node> & beta,
                                          int64_t features,
                                          bool norm,
                                          float q_eps,
                                          float k_eps,
                                          int64_t snapshot_count) {
    // Unmatched graphs need state outputs. Ordinary GDN prefixes preserve that contract.
    auto i64 = [](const Shape & shape, const std::vector<int64_t> & values) {
        return ov::op::v0::Constant::create(ov::element::i64, shape, values);
    };
    auto shape = std::make_shared<ov::op::v3::ShapeOf>(q, ov::element::i64);
    auto batch = std::make_shared<ov::op::v8::Gather>(shape, i64({1}, {0}), i64({}, {0}));
    auto tokens = std::make_shared<ov::op::v8::Gather>(shape, i64({1}, {1}), i64({}, {0}));
    auto perm = i64({4}, {0, 1, 3, 2});
    auto initial = std::make_shared<ov::op::v1::Transpose>(state, perm);
    Output<Node> attention;
    OutputVector snapshots;
    for (int64_t offset = 0; offset < snapshot_count; ++offset) {
        auto end = std::make_shared<ov::op::v1::Maximum>(
            std::make_shared<ov::op::v1::Subtract>(tokens, i64({1}, {offset})), i64({1}, {1}));
        auto prefix = [&](const Output<Node> & value) -> Output<Node> {
            if (offset == 0) {
                return value;
            }
            // Materialize prefixes to avoid the GPU's dynamic Slice alias optimization.
            auto indices = std::make_shared<ov::op::v4::Range>(
                i64({}, {0}), std::make_shared<ov::op::v0::Squeeze>(end), i64({}, {1}), ov::element::i64);
            return std::make_shared<ov::op::v8::Gather>(value, indices, i64({}, {1}));
        };
        auto gdn = std::make_shared<ov::op::internal::GatedDeltaNet>(
            prefix(q), prefix(k), prefix(v), initial, prefix(g), prefix(beta), norm, q_eps, k_eps);
        if (offset == 0) {
            attention = gdn->output(0);
        }
        snapshots.push_back(std::make_shared<ov::op::v1::Reshape>(
            std::make_shared<ov::op::v1::Transpose>(gdn->output(1), perm), i64({4}, {1, 1, -1, features}), false));
    }
    auto valid_rows = std::make_shared<ov::op::v1::Multiply>(
        std::make_shared<ov::op::v1::Minimum>(tokens, i64({1}, {snapshot_count})), batch);
    auto states = std::make_shared<ov::op::v8::Slice>(
        std::make_shared<ov::op::v0::Concat>(snapshots, 2), i64({1}, {0}), valid_rows, i64({1}, {1}), i64({1}, {2}));
    return {attention, states};
}

static OutputVector translate_gdn(const NodeContext & context, const OutputVector * cache_inputs) {
    auto v_shape = context.get_input_shape(2).to_shape();  // [B, T, H_v, S_v]
    auto q_shape = context.get_input_shape(0).to_shape();  // [B, T, H_k, S_k]

    // g [B, T, H_v, 1] gates each head, g [B, T, H_v, S_k] each key dimension (kda); the fused op takes the latter as
    // a rank-4 gate
    const bool kda = context.get_input_shape(3)[3] != 1;
    if (kda && !gdn_per_key_gate_supported()) {
        // the reference loop reads and writes the state in the ggml layout, one state per call
        FRONT_END_OP_CONVERSION_CHECK(!cache_inputs && context.get_output_op_params()[0] == 1 &&
                                          !ggml_openvino_gdn_native_state_enabled(),
                                      "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 "
                                      "gate for recurrent caches, state snapshots or the native state layout");
        return translate_gated_delta_net_ref(context);
    }

    const int64_t H_v = v_shape[2];
    const int64_t S_v = v_shape[3];
    const int64_t H_k = q_shape[2];
    const int64_t snapshot_count = context.get_output_op_params()[0];

    // v is usually a VIEW of the fused qkv conv output, [S_v, H_v, T, B] over [conv_dim, T, B], with the heads packed
    // in each row: a Slice of that row plus the Reshape below. Any other view layout, e.g. heads padded to a wider
    // row, goes through the generic view resolution, which already returns [B, T, H_v, S_v].
    const bool v_is_view = context.get_view_input_size(2) > 0;
    bool v_packed_heads = true;
    if (v_is_view) {
        const auto v_stride = context.get_view_input_stride(2, 0);  // OV order: v_stride[3] = nb[0], v_stride[2] = nb[1]
        v_packed_heads = v_stride.size() == 4 && v_stride[2] == (size_t) S_v * v_stride[3];
    }

    auto q = context.get_input(0);
    auto k = context.get_input(1);
    auto v = v_packed_heads ? process_view_input(context, 2, H_v * S_v, 3) : process_view_input_new(context, 2);
    auto g = context.get_input(3);
    auto beta = context.get_input(4);
    auto state = context.get_input(5);

    Output<Node> raw_q, raw_k;
    float q_eps = 1e-6f, k_eps = 1e-6f;
    const bool fuse_qk_l2norm = ggml_openvino_is_gpu() &&
        match_gdn_l2_norm(q, raw_q, q_eps) && match_gdn_l2_norm(k, raw_k, k_eps);
    if (fuse_qk_l2norm) {
        // Keep head tiling below; GDN applies normalization per head and keeps its attention scale.
        q = raw_q;
        k = raw_k;
    }

    if (context.get_op_case() == 1 && ggml_openvino_gdn_prescale_enabled()) {
        // the output is linear in q and the state does not depend on q; the next rms_norm removes the scale
        q = std::make_shared<ov::op::v1::Multiply>(
            q, ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {ggml_openvino_gdn_q_scale()}));
    }

    // ggml maps GQA heads in tiled order, while OV GDN maps repeated heads in grouped order.
    if (H_v != H_k) {
        const int64_t repeat = H_v / H_k;
        auto repeats = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, repeat, 1});
        q = std::make_shared<ov::op::v0::Tile>(q, repeats);
        k = std::make_shared<ov::op::v0::Tile>(k, repeats);
    }

    if (v_is_view && v_packed_heads) {
        // Same as l2_norm case 1
        v = std::make_shared<ov::op::v0::Squeeze>(v, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
        auto v_shape = context.get_input_shape(2).to_shape();
        std::vector<int64_t> reshape_pattern = {0, 0, (int64_t) v_shape[2], (int64_t) v_shape[3]};
        v = std::make_shared<ov::op::v1::Reshape>(
            v, ov::op::v0::Constant::create(ov::element::i64, {4}, reshape_pattern), true);
    }

    // ggml state layout (OV notation): [B, H_v, value_dim, key_dim]
    // GatedDeltaNet op expects: [B, H_v, key_dim, value_dim]
    // With native state the buffer already holds the op layout, so skip both transposes. This is safe because
    // resets and slot copies move whole states, and supports_op aborts instead of falling back to CPU.
    const bool native_state = ggml_openvino_gdn_native_state_enabled();
    auto state_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, 1, 3, 2});
    if (!native_state && !cache_inputs && snapshot_count == 1) {
        state = std::make_shared<ov::op::v1::Transpose>(state, state_perm);
    }

    if (!kda) {
        g = std::make_shared<ov::op::v0::Squeeze>(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
    }
    beta = std::make_shared<ov::op::v0::Squeeze>(beta, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));

    if (context.has_input("chunk_valid_len")) {
        // The last prefill chunk is padded with fabricated tokens. The recurrence is
        //   S_t = S_{t-1} * exp(g_t) + k_t (x) ((v_t - S_{t-1}^T k_t) * beta_t)
        // so forcing g = 0 and beta = 0 makes a padded step an exact identity and keeps the final
        // state equal to the state after the last real token. Attention output at those positions
        // is garbage but never read.
        const auto & g_ps = g.get_partial_shape();
        FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps[1].is_static(),
                                      "GATED_DELTA_NET pad masking requires a static token dimension");
        const int64_t n_tokens = g_ps[1].get_length();
        std::vector<int64_t> positions(n_tokens);
        std::iota(positions.begin(), positions.end(), 0);
        auto valid = std::make_shared<ov::op::v1::Less>(
            ov::op::v0::Constant::create(ov::element::i64, {(size_t) n_tokens}, positions),
            context.get_input("chunk_valid_len"));
        auto mask = std::make_shared<ov::op::v0::Unsqueeze>(
            std::make_shared<ov::op::v0::Convert>(valid, g.get_element_type()),
            ov::op::v0::Constant::create(ov::element::i64, {2}, std::vector<int64_t>{0, 2}));
        beta = std::make_shared<ov::op::v1::Multiply>(beta, mask);
        if (kda) {
            mask = std::make_shared<ov::op::v0::Unsqueeze>(mask,
                                                           ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
        }
        g = std::make_shared<ov::op::v1::Multiply>(g, mask);
    }

    // std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape()
    //           << ", v=" << v.get_partial_shape() << ", g=" << g.get_partial_shape()
    //           << ", beta=" << beta.get_partial_shape() << ", state=" << state.get_partial_shape() << std::endl;

#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
    if (cache_inputs) {
        OutputVector args{q, k, v, (*cache_inputs)[0], g, beta};
        args.insert(args.end(), cache_inputs->begin() + 1, cache_inputs->end());
        auto fused = std::make_shared<ov::op::internal::RecurrentGatedDeltaNetUpdate>(
            args, fuse_qk_l2norm, q_eps, k_eps, snapshot_count);
        fused->set_friendly_name(context.get_name() + "/RecurrentGatedDeltaNetUpdate");
        // The matched state VIEW is consumed only by the overridden full-cache
        // writeback. Route that cache directly instead of materializing snapshots.
        if (context.get_output_names().size() == 3) {
            return {fused->output(0), fused->output(0), (*cache_inputs)[0]};
        }
        return {fused->output(0), (*cache_inputs)[0]};
    }
#endif

    Output<Node> attn_4d, states;
    if (snapshot_count > 1) {
        auto outputs = translate_gdn_snapshots(q, k, v, state, g, beta, H_v * S_v * q_shape[3],
                                               fuse_qk_l2norm, q_eps, k_eps, snapshot_count);
        attn_4d = outputs[0];
        states = outputs[1];
    } else {
        auto outputs = make_gated_delta_net(q, k, v, state, g, beta, fuse_qk_l2norm, q_eps, k_eps);
        attn_4d = outputs[0];
        if (native_state) {
            states = outputs[1];
        } else {
            states = std::make_shared<ov::op::v1::Transpose>(outputs[1], state_perm);
        }
    }
    if (snapshot_count == 1 && context.get_output_names().size() == 2) {
        // The canonical graph consumes the packed GGML result only through separate attention
        // and state VIEWs. Publish the native outputs under those VIEW names to avoid
        // flatten -> concat -> reshape -> slice -> reshape chains. This also works for B > 1.
        return rename_outputs_with_suffix({attn_4d, states}, context.get_name());
    }

    auto flat_shape_1d = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});
    auto attn = std::make_shared<ov::op::v1::Reshape>(attn_4d, flat_shape_1d, false);
    auto new_state = std::make_shared<ov::op::v1::Reshape>(states, flat_shape_1d, false);
    auto packed = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{attn, new_state}, 0);
    auto out_shape = ov::op::v0::Constant::create(ov::element::i64, {4},
                                                  std::vector<int64_t>{1, 1, -1 /*T * B + S_v * B*/, S_v * H_v});
    auto res = std::make_shared<ov::op::v1::Reshape>(packed, out_shape, false);

    if (context.get_output_names().size() == 3) {
        auto flat_states = std::make_shared<ov::op::v1::Reshape>(
            states,
            ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, -1, S_v * S_v * H_v}),
            false);
        return rename_outputs_with_suffix({res, attn_4d, flat_states}, context.get_name());
    }
    return rename_outputs_with_suffix({res}, context.get_name());
}

OutputVector translate_gated_delta_net(const NodeContext & context) {
    return translate_gdn(context, nullptr);
}

#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs) {
    return translate_gdn(context, &cache_inputs);
}
#endif

static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
    num_inputs_check(context, 6, 6);
    FRONT_END_OP_CONVERSION_CHECK(!context.has_input("chunk_valid_len"),
                                  "GATED_DELTA_NET reference loop does not support padded prefill chunks");

    // Inputs (OV shapes are reversed from ggml):
    // ggml: q[S_k, H_k, T, B], k[S_k, H_k, T, B], v[S_v, H_v, T, B]
    // OV:   q[B, T, H_k, S_k], k[B, T, H_k, S_k], v[B, T, H_v, S_v]
    // ggml: g[1 or S_v, H_v, T, B], beta[1, H_v, T, B]
    // OV:   g[B, T, H_v, 1 or S_v], beta[B, T, H_v, 1]
    // ggml: state[S_v, S_v, H_v, B]
    // OV:   state[B, H_v, S_v, S_v]
    auto q = process_view_input_new(context, 0);
    auto k = process_view_input_new(context, 1);
    auto v = process_view_input_new(context, 2);
    auto g = process_view_input_new(context, 3);
    auto beta = process_view_input_new(context, 4);
    auto state = process_view_input_new(context, 5);

    auto v_shape = context.get_input_shape(2).to_shape();  // [B, T, H_v, S_v]
    auto q_shape = context.get_input_shape(0).to_shape();  // [B, T, H_k, S_k]
    auto g_shape = context.get_input_shape(3).to_shape();  // [B, T, H_v, 1 or S_v]

    // The token count T is dynamic: shapes below use -1 for it and the loop runs once per input token.
    const int64_t B = v_shape[0];
    const int64_t H_v = v_shape[2];
    const int64_t S_v = v_shape[3];
    const int64_t H_k = q_shape[2];
    const bool kda = (g_shape[3] == (size_t) S_v);

    const int64_t rq1 = H_v / H_k;  // head repeat factor
    const float scale = 1.0f / std::sqrt((float) S_v);

    auto axis_1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
    auto axis_2 = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});

    // Transpose inputs from [B, T, H, S] to [B, H, T, S] for easier per-head processing
    auto perm_0213 = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, 2, 1, 3});
    auto q_t = std::make_shared<ov::op::v1::Transpose>(q, perm_0213);        // [B, H_k, T, S_k]
    auto k_t = std::make_shared<ov::op::v1::Transpose>(k, perm_0213);        // [B, H_k, T, S_k]
    auto v_t = std::make_shared<ov::op::v1::Transpose>(v, perm_0213);        // [B, H_v, T, S_v]
    auto g_t = std::make_shared<ov::op::v1::Transpose>(g, perm_0213);        // [B, H_v, T, 1 or S_v]
    auto beta_t = std::make_shared<ov::op::v1::Transpose>(beta, perm_0213);  // [B, H_v, T, 1]

    // Broadcast Q, K heads to match V heads if GQA is used (H_v > H_k)
    ov::Output<ov::Node> q_bh = q_t;
    ov::Output<ov::Node> k_bh = k_t;
    if (rq1 > 1) {
        auto q_unsq = std::make_shared<ov::op::v0::Unsqueeze>(q_t, axis_2);  // [B, H_k, 1, T, S]
        auto k_unsq = std::make_shared<ov::op::v0::Unsqueeze>(k_t, axis_2);  // [B, H_k, 1, T, S]

        auto bcast_shape = ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{1, 1, rq1, 1, 1});
        auto q_bcast =
            std::make_shared<ov::op::v3::Broadcast>(q_unsq, bcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);
        auto k_bcast =
            std::make_shared<ov::op::v3::Broadcast>(k_unsq, bcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);

        // Transpose [B, H_k, rq1, T, S] -> [B, rq1, H_k, T, S] so that reshape merges
        // as [rq1, H_k] giving repeat-blocks pattern matching CPU: iq1 = iv1 % H_k
        auto perm_5d = ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{0, 2, 1, 3, 4});
        auto q_transposed = std::make_shared<ov::op::v1::Transpose>(q_bcast, perm_5d);
        auto k_transposed = std::make_shared<ov::op::v1::Transpose>(k_bcast, perm_5d);

        auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, -1, S_v});
        q_bh = std::make_shared<ov::op::v1::Reshape>(q_transposed, new_shape, false);
        k_bh = std::make_shared<ov::op::v1::Reshape>(k_transposed, new_shape, false);
    }

    // Merge batch and head dims: [B*H_v, T, S_v]
    auto merge_bh = [&](const ov::Output<ov::Node> & x, int64_t last_dim) {
        auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, -1, last_dim});
        return std::make_shared<ov::op::v1::Reshape>(x, shape, false);
    };

    auto q_m = merge_bh(q_bh, S_v);           // [B*H_v, T, S_v]
    auto k_m = merge_bh(k_bh, S_v);           // [B*H_v, T, S_v]
    auto v_m = merge_bh(v_t, S_v);            // [B*H_v, T, S_v]
    auto g_m = merge_bh(g_t, kda ? S_v : 1);  // [B*H_v, T, 1 or S_v]
    auto beta_m = merge_bh(beta_t, 1);        // [B*H_v, T, 1]

    // State: [B, H_v, S_v, S_v] -> [B*H_v, S_v, S_v]
    auto state_shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, S_v, S_v});
    auto state_m = std::make_shared<ov::op::v1::Reshape>(state, state_shape, false);

    auto scale_const = ov::op::v0::Constant::create(ov::element::f32, {}, std::vector<float>{scale});

    // --- Build Loop body ---
    // Body parameters (no iteration counter needed, use -1 in special ports)
    auto body_state = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
    auto body_q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
    auto body_k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
    auto body_v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
    auto body_g = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
    auto body_beta = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
    auto body_iter = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1});

    // Condition output (always true - we rely on trip_count for termination)
    auto body_cond_out = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector<bool>{true});

    // Gather current token from invariant inputs using iteration counter
    auto q_t_cur = std::make_shared<ov::op::v8::Gather>(body_q, body_iter, axis_1);     // [B*H_v, 1, S_v]
    auto k_t_cur = std::make_shared<ov::op::v8::Gather>(body_k, body_iter, axis_1);     // [B*H_v, 1, S_v]
    auto v_t_cur = std::make_shared<ov::op::v8::Gather>(body_v, body_iter, axis_1);     // [B*H_v, 1, S_v]
    auto g_t_cur = std::make_shared<ov::op::v8::Gather>(body_g, body_iter, axis_1);     // [B*H_v, 1, 1 or S_v]
    auto b_t_cur = std::make_shared<ov::op::v8::Gather>(body_beta, body_iter, axis_1);  // [B*H_v, 1, 1]

    // Squeeze token dim
    auto q_cur = std::make_shared<ov::op::v0::Squeeze>(q_t_cur, axis_1);  // [B*H_v, S_v]
    auto k_cur = std::make_shared<ov::op::v0::Squeeze>(k_t_cur, axis_1);  // [B*H_v, S_v]
    auto v_cur = std::make_shared<ov::op::v0::Squeeze>(v_t_cur, axis_1);  // [B*H_v, S_v]
    auto g_cur = std::make_shared<ov::op::v0::Squeeze>(g_t_cur, axis_1);  // [B*H_v, 1 or S_v]
    auto b_cur = std::make_shared<ov::op::v0::Squeeze>(b_t_cur, axis_1);  // [B*H_v, 1]

    // Step 1: Apply decay gate to state
    auto exp_g = std::make_shared<ov::op::v0::Exp>(g_cur);                                // [B*H_v, 1 or S_v]
    auto exp_g_unsq = std::make_shared<ov::op::v0::Unsqueeze>(exp_g, axis_1);             // [B*H_v, 1, 1 or S_v]
    auto state_decayed = std::make_shared<ov::op::v1::Multiply>(body_state, exp_g_unsq);  // [B*H_v, S_v, S_v]

    // Step 2: delta = (v - S @ k) * beta
    auto k_col = std::make_shared<ov::op::v0::Unsqueeze>(k_cur, axis_2);                 // [B*H_v, S_v, 1]
    auto sk = std::make_shared<ov::op::v0::MatMul>(state_decayed, k_col, false, false);  // [B*H_v, S_v, 1]
    auto sk_sq = std::make_shared<ov::op::v0::Squeeze>(sk, axis_2);                      // [B*H_v, S_v]
    auto v_minus_sk = std::make_shared<ov::op::v1::Subtract>(v_cur, sk_sq);              // [B*H_v, S_v]
    auto delta = std::make_shared<ov::op::v1::Multiply>(v_minus_sk, b_cur);              // [B*H_v, S_v]

    // Step 3: state += outer(delta, k)
    auto delta_col = std::make_shared<ov::op::v0::Unsqueeze>(delta, axis_2);                 // [B*H_v, S_v, 1]
    auto k_row = std::make_shared<ov::op::v0::Unsqueeze>(k_cur, axis_1);                     // [B*H_v, 1, S_v]
    auto outer_prod = std::make_shared<ov::op::v0::MatMul>(delta_col, k_row, false, false);  // [B*H_v, S_v, S_v]
    auto state_updated = std::make_shared<ov::op::v1::Add>(state_decayed, outer_prod);       // [B*H_v, S_v, S_v]

    // Step 4: attn_out = S @ q * scale
    auto q_col = std::make_shared<ov::op::v0::Unsqueeze>(q_cur, axis_2);                 // [B*H_v, S_v, 1]
    auto sq = std::make_shared<ov::op::v0::MatMul>(state_updated, q_col, false, false);  // [B*H_v, S_v, 1]
    auto sq_squeezed = std::make_shared<ov::op::v0::Squeeze>(sq, axis_2);                // [B*H_v, S_v]
    auto attn_out = std::make_shared<ov::op::v1::Multiply>(sq_squeezed, scale_const);    // [B*H_v, S_v]

    // Unsqueeze attn_out to [B*H_v, 1, S_v] for scan output concatenation
    auto attn_out_unsq = std::make_shared<ov::op::v0::Unsqueeze>(attn_out, axis_1);  // [B*H_v, 1, S_v]

    // --- Assemble Loop ---
    // Body: results = [condition, state_updated, attn_out_unsq]
    auto body = std::make_shared<ov::Model>(
        ov::OutputVector{body_cond_out, state_updated, attn_out_unsq},
        ov::ParameterVector{body_iter, body_state, body_q, body_k, body_v, body_g, body_beta});

    auto vm_shape = std::make_shared<ov::op::v3::ShapeOf>(v_m, ov::element::i64);
    auto trip_count =
        std::make_shared<ov::op::v8::Gather>(vm_shape, axis_1, ov::op::v0::Constant::create(ov::element::i64, {}, {0}));
    auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector<bool>{true});

    auto loop = std::make_shared<ov::op::v5::Loop>(trip_count, exec_cond);
    loop->set_function(body);
    loop->set_special_body_ports(ov::op::v5::Loop::SpecialBodyPorts{0, 0});

    // Carried state: feeds back from body output 1 to body_state param
    loop->set_merged_input(body_state, state_m, state_updated);
    // Invariant inputs: passed through unchanged each iteration
    loop->set_invariant_input(body_q, q_m);
    loop->set_invariant_input(body_k, k_m);
    loop->set_invariant_input(body_v, v_m);
    loop->set_invariant_input(body_g, g_m);
    loop->set_invariant_input(body_beta, beta_m);

    // Loop outputs:
    // 1) Final state (last iteration value of state_updated)
    auto final_state_out = loop->get_iter_value(state_updated, -1);  // [B*H_v, S_v, S_v]
    // 2) Concatenated attention outputs across all iterations along axis 1
    auto attn_concat_out = loop->get_concatenated_slices(attn_out_unsq, 0, 1, 1, -1, 1);  // [B*H_v, T, S_v]

    // --- Pack outputs to match ggml layout ---
    // ggml output ne = {S_v*H, T*B + S_v*B, 1, 1} -> OV [1, 1, T*B+S_v*B, S_v*H_v]
    // attn: [B, T, H_v, S_v] row-major, state: [B, H_v, S_v, S_v] row-major

    // attn: [B*H_v, T, S_v] -> [B, H_v, T, S_v] -> transpose to [B, T, H_v, S_v] -> flatten
    auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, -1, S_v});
    auto attn_4d = std::make_shared<ov::op::v1::Reshape>(attn_concat_out, attn_4d_shape, false);
    auto attn_perm = std::make_shared<ov::op::v1::Transpose>(attn_4d, perm_0213);  // [B, T, H_v, S_v]

    auto flat_shape_1d = ov::op::v0::Constant::create(ov::element::i64, {1}, std::vector<int64_t>{-1});
    auto attn_1d = std::make_shared<ov::op::v1::Reshape>(attn_perm, flat_shape_1d, false);

    // state: [B*H_v, S_v, S_v] -> [B, H_v, S_v, S_v] -> flatten
    auto state_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, S_v, S_v});
    auto state_4d = std::make_shared<ov::op::v1::Reshape>(final_state_out, state_4d_shape, false);
    if (context.get_output_names().size() == 2) {
        // Match the fused translator's direct attention/state contract.
        return rename_outputs_with_suffix({attn_perm, state_4d}, context.get_name());
    }

    auto state_1d = std::make_shared<ov::op::v1::Reshape>(state_4d, flat_shape_1d, false);

    // Concat [attn | state] and reshape to final output
    auto packed = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{attn_1d, state_1d}, 0);
    auto out_shape =
        ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, -1, S_v * H_v});
    auto res = std::make_shared<ov::op::v1::Reshape>(packed, out_shape, false);

    return rename_outputs_with_suffix({res}, context.get_name());
}

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