interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-openvino / openvino / op / gated_delta_net.cpp

407 lines · 22344 bytes Raw Blame History
1#include "gated_delta_net.hpp"
2
3#include "../node_context.h"
4#include "../op_table.h"
5#include "../utils.h"
6#include "ggml-openvino/ggml-openvino-extra.h"
7
8#include <cmath>
9#include <cstdint>
10#include <memory>
11#include <numeric>
12#include <openvino/op/add.hpp>
13#include <openvino/op/broadcast.hpp>
14#include <openvino/op/concat.hpp>
15#include <openvino/op/constant.hpp>
16#include <openvino/op/convert.hpp>
17#include <openvino/op/divide.hpp>
18#include <openvino/op/exp.hpp>
19#include <openvino/op/gather.hpp>
20#include <openvino/op/less.hpp>
21#include <openvino/op/loop.hpp>
22#include <openvino/op/matmul.hpp>
23#include <openvino/op/multiply.hpp>
24#include <openvino/op/reduce_mean.hpp>
25#include <openvino/op/reshape.hpp>
26#include <openvino/op/squeeze.hpp>
27#include <openvino/op/sqrt.hpp>
28#include <openvino/op/subtract.hpp>
29#include <openvino/op/tile.hpp>
30#include <openvino/op/transpose.hpp>
31#include <openvino/op/unsqueeze.hpp>
32#include <vector>
33
34namespace ov {
35namespace frontend {
36namespace ggml {
37namespace op {
38
39static OutputVector translate_gated_delta_net_ref(const NodeContext & context);
40
41static bool match_gdn_l2_norm(const Output<Node> & normalized, Output<Node> & input, float & eps) {
42 // Match the RMSNorm decomposition emitted by translate_rms_norm, followed by GGML SCALE.
43 const auto scale = ov::as_type_ptr<ov::op::v1::Multiply>(normalized.get_node_shared_ptr());
44 if (!scale) {
45 return false;
46 }
47 const auto factor = ov::as_type_ptr<ov::op::v0::Constant>(scale->get_input_node_shared_ptr(1));
48 const auto rms = ov::as_type_ptr<ov::op::v1::Multiply>(scale->get_input_node_shared_ptr(0));
49 if (!factor || ov::shape_size(factor->get_shape()) != 1 || !rms) {
50 return false;
51 }
52 const auto x = rms->input_value(0);
53 const auto & shape = x.get_partial_shape();
54 if (x.get_element_type() != ov::element::f32 || shape.rank() != 4 || shape[3].is_dynamic() ||
55 shape[3].get_length() <= 0 || normalized.get_partial_shape() != shape) {
56 return false;
57 }
58 const float dim = static_cast<float>(shape[3].get_length());
59 if (factor->cast_vector<float>()[0] != 1.0f / std::sqrt(dim)) {
60 return false;
61 }
62 const auto reciprocal = ov::as_type_ptr<ov::op::v1::Divide>(rms->get_input_node_shared_ptr(1));
63 if (!reciprocal) {
64 return false;
65 }
66 const auto one = ov::as_type_ptr<ov::op::v0::Constant>(reciprocal->get_input_node_shared_ptr(0));
67 const auto root = ov::as_type_ptr<ov::op::v0::Sqrt>(reciprocal->get_input_node_shared_ptr(1));
68 if (!one || ov::shape_size(one->get_shape()) != 1 || one->cast_vector<float>()[0] != 1.0f || !root) {
69 return false;
70 }
71 const auto add = ov::as_type_ptr<ov::op::v1::Add>(root->get_input_node_shared_ptr(0));
72 if (!add) {
73 return false;
74 }
75 const auto mean = ov::as_type_ptr<ov::op::v1::ReduceMean>(add->get_input_node_shared_ptr(0));
76 const auto rms_eps = ov::as_type_ptr<ov::op::v0::Constant>(add->get_input_node_shared_ptr(1));
77 if (!mean || !mean->get_keep_dims() || !rms_eps || ov::shape_size(rms_eps->get_shape()) != 1) {
78 return false;
79 }
80 const auto axes = ov::as_type_ptr<ov::op::v0::Constant>(mean->get_input_node_shared_ptr(1));
81 const auto square = ov::as_type_ptr<ov::op::v1::Multiply>(mean->get_input_node_shared_ptr(0));
82 if (!axes || axes->cast_vector<int64_t>() != std::vector<int64_t>{-1} || !square ||
83 square->input_value(0) != x || square->input_value(1) != x) {
84 return false;
85 }
86 // RMSNorm(x, rms_eps) / sqrt(D) = x / sqrt(sum(x*x) + D*rms_eps).
87 eps = dim * rms_eps->cast_vector<float>()[0];
88 if (!std::isfinite(eps) || eps <= 0.0f) {
89 return false;
90 }
91 input = x;
92 return true;
93}
94
95OutputVector translate_gated_delta_net(const NodeContext & context) {
96 auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v]
97 auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]
98
99 // Fused GatedDeltaNet op only supports scalar gate (kda=0).
100 // Fall back to reference implementation for per-key-dimension gating.
101 // if (kda) {
102 // return translate_gated_delta_net_ref(context);
103 // }
104
105 // const int64_t B = v_shape[0];
106 // const int64_t T = v_shape[1];
107 const int64_t H_v = v_shape[2];
108 const int64_t S_v = v_shape[3];
109 const int64_t H_k = q_shape[2];
110 // const int64_t S_k = q_shape[3];
111
112 auto q = context.get_input(0);
113 auto k = context.get_input(1);
114 auto v = process_view_input(context, 2, H_v * S_v, 3);
115 auto g = context.get_input(3);
116 auto beta = context.get_input(4);
117 auto state = context.get_input(5);
118
119 Output<Node> raw_q, raw_k;
120 float q_eps = 1e-6f, k_eps = 1e-6f;
121 const bool fuse_qk_l2norm = ggml_openvino_is_gpu() &&
122 match_gdn_l2_norm(q, raw_q, q_eps) && match_gdn_l2_norm(k, raw_k, k_eps);
123 if (fuse_qk_l2norm) {
124 // Keep head tiling below; GDN applies normalization per head and keeps its attention scale.
125 q = raw_q;
126 k = raw_k;
127 }
128
129 // ggml maps GQA heads in tiled order, while OV GDN maps repeated heads in grouped order.
130 if (H_v != H_k) {
131 const int64_t repeat = H_v / H_k;
132 auto repeats = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, repeat, 1});
133 q = std::make_shared<ov::op::v0::Tile>(q, repeats);
134 k = std::make_shared<ov::op::v0::Tile>(k, repeats);
135 }
136
137 if (context.get_view_input_size(2)) {
138 // Same as l2_norm case 1
139 v = std::make_shared<ov::op::v0::Squeeze>(v, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
140 auto v_shape = context.get_input_shape(2).to_shape();
141 std::vector<int64_t> reshape_pattern = {0, 0, (int64_t) v_shape[2], (int64_t) v_shape[3]};
142 v = std::make_shared<ov::op::v1::Reshape>(
143 v, ov::op::v0::Constant::create(ov::element::i64, {4}, reshape_pattern), true);
144 }
145
146 // ggml state layout (OV notation): [B, H_v, value_dim, key_dim]
147 // GatedDeltaNet op expects: [B, H_v, key_dim, value_dim]
148 auto state_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, 1, 3, 2});
149 state = std::make_shared<ov::op::v1::Transpose>(state, state_perm);
150
151 g = std::make_shared<ov::op::v0::Squeeze>(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
152 beta = std::make_shared<ov::op::v0::Squeeze>(beta, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
153
154 if (context.has_input("chunk_valid_len")) {
155 // The last prefill chunk is padded with fabricated tokens. The recurrence is
156 // S_t = S_{t-1} * exp(g_t) + k_t (x) ((v_t - S_{t-1}^T k_t) * beta_t)
157 // so forcing g = 0 and beta = 0 makes a padded step an exact identity and keeps the final
158 // state equal to the state after the last real token. Attention output at those positions
159 // is garbage but never read.
160 const auto & g_ps = g.get_partial_shape();
161 FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps.rank().get_length() == 3 && g_ps[1].is_static(),
162 "GATED_DELTA_NET pad masking requires a static token dimension");
163 const int64_t n_tokens = g_ps[1].get_length();
164 std::vector<int64_t> positions(n_tokens);
165 std::iota(positions.begin(), positions.end(), 0);
166 auto valid = std::make_shared<ov::op::v1::Less>(
167 ov::op::v0::Constant::create(ov::element::i64, {(size_t) n_tokens}, positions),
168 context.get_input("chunk_valid_len"));
169 auto mask = std::make_shared<ov::op::v0::Unsqueeze>(
170 std::make_shared<ov::op::v0::Convert>(valid, g.get_element_type()),
171 ov::op::v0::Constant::create(ov::element::i64, {2}, std::vector<int64_t>{0, 2}));
172 g = std::make_shared<ov::op::v1::Multiply>(g, mask);
173 beta = std::make_shared<ov::op::v1::Multiply>(beta, mask);
174 }
175
176 // std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape()
177 // << ", v=" << v.get_partial_shape() << ", g=" << g.get_partial_shape()
178 // << ", beta=" << beta.get_partial_shape() << ", state=" << state.get_partial_shape() << std::endl;
179
180 auto gdn = std::make_shared<ov::op::internal::GatedDeltaNet>(q, k, v, state, g, beta, fuse_qk_l2norm, q_eps, k_eps);
181 auto attn_4d = gdn->output(0);
182 auto state_4d = gdn->output(1); // [B, H_v, key_dim, value_dim]
183
184 // std::cout << "GatedDeltaNet output shapes: attn=" << gdn->output(0).get_partial_shape()
185 // << ", new_state=" << gdn->output(1).get_partial_shape() << std::endl;
186
187 // Transpose output state back to ggml layout [B, H_v, value_dim, key_dim]
188 auto state_transposed = std::make_shared<ov::op::v1::Transpose>(state_4d, state_perm);
189 if (context.get_output_names().size() == 2) {
190 // The canonical graph consumes the packed GGML result only through separate attention
191 // and state VIEWs. Publish the native outputs under those VIEW names to avoid
192 // flatten -> concat -> reshape -> slice -> reshape chains. This also works for B > 1.
193 return rename_outputs_with_suffix({attn_4d, state_transposed}, context.get_name());
194 }
195
196 auto flat_shape_1d = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});
197 auto attn = std::make_shared<ov::op::v1::Reshape>(attn_4d, flat_shape_1d, false);
198 auto new_state = std::make_shared<ov::op::v1::Reshape>(state_transposed, flat_shape_1d, false);
199 auto packed = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{attn, new_state}, 0);
200 auto out_shape = ov::op::v0::Constant::create(ov::element::i64, {4},
201 std::vector<int64_t>{1, 1, -1 /*T * B + S_v * B*/, S_v * H_v});
202 auto res = std::make_shared<ov::op::v1::Reshape>(packed, out_shape, false);
203
204 return rename_outputs_with_suffix({res}, context.get_name());
205}
206
207static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
208 num_inputs_check(context, 6, 6);
209
210 // Inputs (OV shapes are reversed from ggml):
211 // ggml: q[S_k, H_k, T, B], k[S_k, H_k, T, B], v[S_v, H_v, T, B]
212 // OV: q[B, T, H_k, S_k], k[B, T, H_k, S_k], v[B, T, H_v, S_v]
213 // ggml: g[1 or S_v, H_v, T, B], beta[1, H_v, T, B]
214 // OV: g[B, T, H_v, 1 or S_v], beta[B, T, H_v, 1]
215 // ggml: state[S_v, S_v, H_v, B]
216 // OV: state[B, H_v, S_v, S_v]
217 auto q = process_view_input_new(context, 0);
218 auto k = process_view_input_new(context, 1);
219 auto v = process_view_input_new(context, 2);
220 auto g = process_view_input_new(context, 3);
221 auto beta = process_view_input_new(context, 4);
222 auto state = process_view_input_new(context, 5);
223
224 auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v]
225 auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]
226 auto g_shape = context.get_input_shape(3).to_shape(); // [B, T, H_v, 1 or S_v]
227
228 const int64_t B = v_shape[0];
229 const int64_t T = v_shape[1];
230 const int64_t H_v = v_shape[2];
231 const int64_t S_v = v_shape[3];
232 const int64_t H_k = q_shape[2];
233 const bool kda = (g_shape[3] == (size_t) S_v);
234
235 const int64_t rq1 = H_v / H_k; // head repeat factor
236 const float scale = 1.0f / std::sqrt((float) S_v);
237
238 auto axis_1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
239 auto axis_2 = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});
240
241 // Transpose inputs from [B, T, H, S] to [B, H, T, S] for easier per-head processing
242 auto perm_0213 = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, 2, 1, 3});
243 auto q_t = std::make_shared<ov::op::v1::Transpose>(q, perm_0213); // [B, H_k, T, S_k]
244 auto k_t = std::make_shared<ov::op::v1::Transpose>(k, perm_0213); // [B, H_k, T, S_k]
245 auto v_t = std::make_shared<ov::op::v1::Transpose>(v, perm_0213); // [B, H_v, T, S_v]
246 auto g_t = std::make_shared<ov::op::v1::Transpose>(g, perm_0213); // [B, H_v, T, 1 or S_v]
247 auto beta_t = std::make_shared<ov::op::v1::Transpose>(beta, perm_0213); // [B, H_v, T, 1]
248
249 // Broadcast Q, K heads to match V heads if GQA is used (H_v > H_k)
250 ov::Output<ov::Node> q_bh = q_t;
251 ov::Output<ov::Node> k_bh = k_t;
252 if (rq1 > 1) {
253 auto q_unsq = std::make_shared<ov::op::v0::Unsqueeze>(q_t, axis_2); // [B, H_k, 1, T, S]
254 auto k_unsq = std::make_shared<ov::op::v0::Unsqueeze>(k_t, axis_2); // [B, H_k, 1, T, S]
255
256 auto bcast_shape = ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{1, 1, rq1, 1, 1});
257 auto q_bcast =
258 std::make_shared<ov::op::v3::Broadcast>(q_unsq, bcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);
259 auto k_bcast =
260 std::make_shared<ov::op::v3::Broadcast>(k_unsq, bcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);
261
262 // Transpose [B, H_k, rq1, T, S] -> [B, rq1, H_k, T, S] so that reshape merges
263 // as [rq1, H_k] giving repeat-blocks pattern matching CPU: iq1 = iv1 % H_k
264 auto perm_5d = ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{0, 2, 1, 3, 4});
265 auto q_transposed = std::make_shared<ov::op::v1::Transpose>(q_bcast, perm_5d);
266 auto k_transposed = std::make_shared<ov::op::v1::Transpose>(k_bcast, perm_5d);
267
268 auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, T, S_v});
269 q_bh = std::make_shared<ov::op::v1::Reshape>(q_transposed, new_shape, false);
270 k_bh = std::make_shared<ov::op::v1::Reshape>(k_transposed, new_shape, false);
271 }
272
273 // Merge batch and head dims: [B*H_v, T, S_v]
274 auto merge_bh = [&](const ov::Output<ov::Node> & x, int64_t last_dim) {
275 auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, T, last_dim});
276 return std::make_shared<ov::op::v1::Reshape>(x, shape, false);
277 };
278
279 auto q_m = merge_bh(q_bh, S_v); // [B*H_v, T, S_v]
280 auto k_m = merge_bh(k_bh, S_v); // [B*H_v, T, S_v]
281 auto v_m = merge_bh(v_t, S_v); // [B*H_v, T, S_v]
282 auto g_m = merge_bh(g_t, kda ? S_v : 1); // [B*H_v, T, 1 or S_v]
283 auto beta_m = merge_bh(beta_t, 1); // [B*H_v, T, 1]
284
285 // State: [B, H_v, S_v, S_v] -> [B*H_v, S_v, S_v]
286 auto state_shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, S_v, S_v});
287 auto state_m = std::make_shared<ov::op::v1::Reshape>(state, state_shape, false);
288
289 auto scale_const = ov::op::v0::Constant::create(ov::element::f32, {}, std::vector<float>{scale});
290
291 // --- Build Loop body ---
292 // Body parameters (no iteration counter needed, use -1 in special ports)
293 auto body_state = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
294 auto body_q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
295 auto body_k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
296 auto body_v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
297 auto body_g = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
298 auto body_beta = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());
299 auto body_iter = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1});
300
301 // Condition output (always true - we rely on trip_count for termination)
302 auto body_cond_out = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector<bool>{true});
303
304 // Gather current token from invariant inputs using iteration counter
305 auto q_t_cur = std::make_shared<ov::op::v8::Gather>(body_q, body_iter, axis_1); // [B*H_v, 1, S_v]
306 auto k_t_cur = std::make_shared<ov::op::v8::Gather>(body_k, body_iter, axis_1); // [B*H_v, 1, S_v]
307 auto v_t_cur = std::make_shared<ov::op::v8::Gather>(body_v, body_iter, axis_1); // [B*H_v, 1, S_v]
308 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]
309 auto b_t_cur = std::make_shared<ov::op::v8::Gather>(body_beta, body_iter, axis_1); // [B*H_v, 1, 1]
310
311 // Squeeze token dim
312 auto q_cur = std::make_shared<ov::op::v0::Squeeze>(q_t_cur, axis_1); // [B*H_v, S_v]
313 auto k_cur = std::make_shared<ov::op::v0::Squeeze>(k_t_cur, axis_1); // [B*H_v, S_v]
314 auto v_cur = std::make_shared<ov::op::v0::Squeeze>(v_t_cur, axis_1); // [B*H_v, S_v]
315 auto g_cur = std::make_shared<ov::op::v0::Squeeze>(g_t_cur, axis_1); // [B*H_v, 1 or S_v]
316 auto b_cur = std::make_shared<ov::op::v0::Squeeze>(b_t_cur, axis_1); // [B*H_v, 1]
317
318 // Step 1: Apply decay gate to state
319 auto exp_g = std::make_shared<ov::op::v0::Exp>(g_cur); // [B*H_v, 1 or S_v]
320 auto exp_g_unsq = std::make_shared<ov::op::v0::Unsqueeze>(exp_g, axis_1); // [B*H_v, 1, 1 or S_v]
321 auto state_decayed = std::make_shared<ov::op::v1::Multiply>(body_state, exp_g_unsq); // [B*H_v, S_v, S_v]
322
323 // Step 2: delta = (v - S @ k) * beta
324 auto k_col = std::make_shared<ov::op::v0::Unsqueeze>(k_cur, axis_2); // [B*H_v, S_v, 1]
325 auto sk = std::make_shared<ov::op::v0::MatMul>(state_decayed, k_col, false, false); // [B*H_v, S_v, 1]
326 auto sk_sq = std::make_shared<ov::op::v0::Squeeze>(sk, axis_2); // [B*H_v, S_v]
327 auto v_minus_sk = std::make_shared<ov::op::v1::Subtract>(v_cur, sk_sq); // [B*H_v, S_v]
328 auto delta = std::make_shared<ov::op::v1::Multiply>(v_minus_sk, b_cur); // [B*H_v, S_v]
329
330 // Step 3: state += outer(delta, k)
331 auto delta_col = std::make_shared<ov::op::v0::Unsqueeze>(delta, axis_2); // [B*H_v, S_v, 1]
332 auto k_row = std::make_shared<ov::op::v0::Unsqueeze>(k_cur, axis_1); // [B*H_v, 1, S_v]
333 auto outer_prod = std::make_shared<ov::op::v0::MatMul>(delta_col, k_row, false, false); // [B*H_v, S_v, S_v]
334 auto state_updated = std::make_shared<ov::op::v1::Add>(state_decayed, outer_prod); // [B*H_v, S_v, S_v]
335
336 // Step 4: attn_out = S @ q * scale
337 auto q_col = std::make_shared<ov::op::v0::Unsqueeze>(q_cur, axis_2); // [B*H_v, S_v, 1]
338 auto sq = std::make_shared<ov::op::v0::MatMul>(state_updated, q_col, false, false); // [B*H_v, S_v, 1]
339 auto sq_squeezed = std::make_shared<ov::op::v0::Squeeze>(sq, axis_2); // [B*H_v, S_v]
340 auto attn_out = std::make_shared<ov::op::v1::Multiply>(sq_squeezed, scale_const); // [B*H_v, S_v]
341
342 // Unsqueeze attn_out to [B*H_v, 1, S_v] for scan output concatenation
343 auto attn_out_unsq = std::make_shared<ov::op::v0::Unsqueeze>(attn_out, axis_1); // [B*H_v, 1, S_v]
344
345 // --- Assemble Loop ---
346 // Body: results = [condition, state_updated, attn_out_unsq]
347 auto body = std::make_shared<ov::Model>(
348 ov::OutputVector{body_cond_out, state_updated, attn_out_unsq},
349 ov::ParameterVector{body_iter, body_state, body_q, body_k, body_v, body_g, body_beta});
350
351 auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{T});
352 auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector<bool>{true});
353
354 auto loop = std::make_shared<ov::op::v5::Loop>(trip_count, exec_cond);
355 loop->set_function(body);
356 loop->set_special_body_ports(ov::op::v5::Loop::SpecialBodyPorts{0, 0});
357
358 // Carried state: feeds back from body output 1 to body_state param
359 loop->set_merged_input(body_state, state_m, state_updated);
360 // Invariant inputs: passed through unchanged each iteration
361 loop->set_invariant_input(body_q, q_m);
362 loop->set_invariant_input(body_k, k_m);
363 loop->set_invariant_input(body_v, v_m);
364 loop->set_invariant_input(body_g, g_m);
365 loop->set_invariant_input(body_beta, beta_m);
366
367 // Loop outputs:
368 // 1) Final state (last iteration value of state_updated)
369 auto final_state_out = loop->get_iter_value(state_updated, -1); // [B*H_v, S_v, S_v]
370 // 2) Concatenated attention outputs across all iterations along axis 1
371 auto attn_concat_out = loop->get_concatenated_slices(attn_out_unsq, 0, 1, 1, -1, 1); // [B*H_v, T, S_v]
372
373 // --- Pack outputs to match ggml layout ---
374 // 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]
375 // attn: [B, T, H_v, S_v] row-major, state: [B, H_v, S_v, S_v] row-major
376
377 // attn: [B*H_v, T, S_v] -> [B, H_v, T, S_v] -> transpose to [B, T, H_v, S_v] -> flatten
378 auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, T, S_v});
379 auto attn_4d = std::make_shared<ov::op::v1::Reshape>(attn_concat_out, attn_4d_shape, false);
380 auto attn_perm = std::make_shared<ov::op::v1::Transpose>(attn_4d, perm_0213); // [B, T, H_v, S_v]
381
382 auto flat_shape_1d = ov::op::v0::Constant::create(ov::element::i64, {1}, std::vector<int64_t>{-1});
383 auto attn_1d = std::make_shared<ov::op::v1::Reshape>(attn_perm, flat_shape_1d, false);
384
385 // state: [B*H_v, S_v, S_v] -> [B, H_v, S_v, S_v] -> flatten
386 auto state_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, S_v, S_v});
387 auto state_4d = std::make_shared<ov::op::v1::Reshape>(final_state_out, state_4d_shape, false);
388 if (context.get_output_names().size() == 2) {
389 // Match the fused translator's direct attention/state contract.
390 return rename_outputs_with_suffix({attn_perm, state_4d}, context.get_name());
391 }
392
393 auto state_1d = std::make_shared<ov::op::v1::Reshape>(state_4d, flat_shape_1d, false);
394
395 // Concat [attn | state] and reshape to final output
396 auto packed = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{attn_1d, state_1d}, 0);
397 auto out_shape =
398 ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, T * B + S_v * B, S_v * H_v});
399 auto res = std::make_shared<ov::op::v1::Reshape>(packed, out_shape, false);
400
401 return rename_outputs_with_suffix({res}, context.get_name());
402}
403
404} // namespace op
405} // namespace ggml
406} // namespace frontend
407} // namespace ov