File size: 16,525 Bytes
a428563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Fused Triton kernel for Sigma GKA token-by-token decoding.

Replaces the PyTorch reference recurrence + a separate Simple-GLA launch:

    H_kk_t = exp(gk_t) H_kk_{t-1} + k_t k_t^T
    q_t_out = a q + b (q H)/F + c (q H^2)/F^2  [+ d (q H^3)/F^3]
    q_mix   = q + alpha (q_t_out - q)
    H_kv_t  = exp(g_t) H_kv_{t-1} + k_t v_t^T
    o_t     = scale * q_mix @ H_kv_t
"""
from typing import Optional, Sequence, Tuple, Union

import torch
import triton
import triton.language as tl
from torch import Tensor

from fla.ops.simple_gla import fused_recurrent_simple_gla
from fla.ops.utils.op import exp
from fla.utils import input_guard


def test_q_kkt_solve_approx_abc(
    q,
    k,
    gk,
    # a=1.0,
    # b=-0.5,
    # c=0.375,
    h0=None,
    learnable_abc=None,
):
    """
    PyTorch reference for the q-phi(KKT) approximation, where phi(x) = x^(-1/2).

    We follow the GLA recurrence to build the per-step key-key state
    H_t = g_t * H_{t-1} + k_t k_t^T, then approximate the (-1/2)-power action
    on q_t by a low-order polynomial in H_t / ||H_t||_F:

        q_t_out = a * q_t
                  + b * (q_t @ H_t) / ||H_t||_F
                  + c * (q_t @ H_t @ H_t) / ||H_t||_F^2

    Args:
        q: Query tensor with shape [B, T, H, D].
        k: Key tensor with shape [B, T, H, D].
        gk: Raw log-gate tensor with shape [B, T, H]. Will be exp'd in use.
            If None, the gate is treated as 1 (no decay).
        a, b, c: Polynomial coefficients. Each may be a scalar or a length-H tensor.
        h0: Optional previous key-key state with shape [B, H, D, D] or [H, D, D].
        learnable_abc: Optional coefficients as [3] or [H, 3]. Overrides a, b, c.

    Returns:
        o: Output tensor with shape [B, T, H, D].
        states: List of length T, each [B, H, D, D] (the per-step H_t).
        fros: List of length T, each [B, H] (per-step Frobenius norm).
    """
    B, T, H, D = q.shape

    if learnable_abc is not None:
        t = learnable_abc
        if not torch.is_tensor(t):
            t = torch.tensor(list(t), device=q.device, dtype=torch.float32)
        else:
            t = t.detach().to(device=q.device)
        if t.numel() == 3:
            a, b, c = t.reshape(3).unbind(0)
        elif t.reshape(-1).numel() == H * 3:
            t = t.reshape(H, 3)
            a, b, c = t[:, 0], t[:, 1], t[:, 2]
        else:
            raise ValueError(
                f"learnable_abc must be [3] or [H, 3] with H={H}, got {tuple(t.shape)}"
            )
    else:
        raise ValueError("learnable_abc must be provided")

    def _coeff(x):
        if torch.is_tensor(x):
            t = x.reshape(-1)
            if t.numel() == 1:
                t = t.expand(H)
            elif t.numel() != H:
                raise ValueError(f"coefficient numel must be 1 or H={H}, got {t.numel()}")
            # [1, H, 1] so it broadcasts with qi / q_state of shape [B, H, D]
            return t.to(device=q.device, dtype=torch.float32).view(1, H, 1)
        return x

    a = _coeff(a)
    b = _coeff(b)
    c = _coeff(c)
    if h0 is None:
        state = torch.zeros(B, H, D, D, dtype=torch.float32, device=q.device)
    else:
        state = h0.to(device=q.device, dtype=torch.float32)
        if state.dim() == 3:
            state = state.unsqueeze(0)
        if state.shape[0] == 1 and B > 1:
            state = state.expand(B, -1, -1, -1).contiguous()
    if gk is None:
        gkk = torch.ones(B, T, H, dtype=torch.float32, device=q.device)
    else:
        gkk = torch.exp(gk.float()).float()

    outs = []
    eps = 1e-12

    for i in range(T):
        ki = k[:, i, :, :]  # [B, H, D]
        # GLA-style state update: H_t = exp(g_t) * H_{t-1} + k_t k_t^T
        state = gkk[:, i, :].view(B, H, 1, 1) * state + ki.unsqueeze(-1) * ki.unsqueeze(-2)
        # Frobenius norm of the current state H_t
        F = torch.norm(state, p='fro', dim=(-2, -1), keepdim=True).squeeze(-1).float()  # [B, H, 1]
        F_safe = F + eps
        qi = q[:, i, :, :].float()  # [B, H, D]
        q_state = ((qi.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float()      # [B, H, D]
        q_state2 = ((q_state.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float()  # [B, H, D]
        out = (a * qi + b * q_state + c * q_state2).to(q.dtype)
        outs.append(out)
        fro = F.squeeze(-1)

    o = torch.stack(outs, dim=1).to(q.dtype)
    return o, state, fro

#############
def test_q_kkt_solve_approx_abcd(q, k, gk, a=1.0, b=-0.5, c=0.375, d=-0.3125,h0=None,learnable_abc=None):
    """
    PyTorch reference for the q-phi(KKT) approximation, where phi(x) = x^(-1/2).

    We follow the GLA recurrence to build the per-step key-key state
    H_t = g_t * H_{t-1} + k_t k_t^T, then approximate the (-1/2)-power action
    on q_t by a cubic polynomial in H_t / ||H_t||_F:

        q_t_out = a * q_t
                  + b * (q_t @ H_t) / ||H_t||_F
                  + c * (q_t @ H_t @ H_t) / ||H_t||_F^2
                  + d * (q_t @ H_t @ H_t @ H_t) / ||H_t||_F^3

    Args:
        q: Query tensor with shape [B, T, H, D].
        k: Key tensor with shape [B, T, H, D].
        gk: Raw log-gate tensor with shape [B, T, H]. Will be exp'd in use.
        a, b, c, d: Polynomial coefficients. Each may be a scalar or a length-H tensor.

    Returns:
        o: Output tensor with shape [B, T, H, D].
        states: List of length T, each [B, H, D, D] (the per-step H_t).
        fros: List of length T, each [B, H] (per-step Frobenius norm).
    """
    B, T, H, D = q.shape
    if learnable_abc is not None:
        t = learnable_abc
        if not torch.is_tensor(t):
            t = torch.tensor(list(t), device=q.device, dtype=torch.float32)
        else:
            t = t.detach().to(device=q.device)
        if t.numel() == 4:
            a, b, c, d = t.reshape(4).unbind(0)
        elif t.reshape(-1).numel() == H * 4:
            t = t.reshape(H, 4)
            a, b, c, d = t[:, 0], t[:, 1], t[:, 2], t[:, 3]
        else:
            raise ValueError(
                f"learnable_abc must be [4] or [H, 4] with H={H}, got {tuple(t.shape)}"
            )

    def _coeff(x):
        if torch.is_tensor(x):
            t = x.reshape(-1)
            if t.numel() == 1:
                t = t.expand(H)
            elif t.numel() != H:
                raise ValueError(f"coefficient numel must be 1 or H={H}, got {t.numel()}")
            return t.to(device=q.device, dtype=torch.float32).view(1, H, 1)
        return x

    a = _coeff(a)
    b = _coeff(b)
    c = _coeff(c)
    d = _coeff(d)
    if h0 is None:
        state = torch.zeros(B, H, D, D, dtype=torch.float32, device=q.device)
    else:
        state = h0.to(device=q.device, dtype=torch.float32)
        if state.dim() == 3:
            state = state.unsqueeze(0)
        if state.shape[0] == 1 and B > 1:
            state = state.expand(B, -1, -1, -1).contiguous()
    if gk is None:
        gkk = torch.ones(B, T, H, dtype=torch.float32, device=q.device)
    else:
        gkk = torch.exp(gk.float()).float()

    outs = []
    eps = 1e-12

    for i in range(T):
        ki = k[:, i, :, :]
        state = gkk[:, i, :].view(B, H, 1, 1) * state + ki.unsqueeze(-1) * ki.unsqueeze(-2)
        F = torch.norm(state, p='fro', dim=(-2, -1), keepdim=True).squeeze(-1).float()
        F_safe = F + eps
        qi = q[:, i, :, :].float()
        q_state = ((qi.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float()      # [B, H, D]
        q_state2 = ((q_state.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float()  # [B, H, D]
        q_state3 = ((q_state2.unsqueeze(-2) @ state).squeeze(-2)/F_safe).float()  # [B, H, D]
        out = (
            a * qi
            + b * q_state
            + c * q_state2
            + d * q_state3
        ).to(q.dtype)
        outs.append(out)
        fro = F.squeeze(-1)
    o = torch.stack(outs, dim=1).to(q.dtype)
    return o, state, fro



def _coeff_last_dim(learnable_abc: Union[Tensor, Sequence[float]]) -> int:
    if torch.is_tensor(learnable_abc):
        if learnable_abc.ndim == 0:
            raise ValueError("learnable_abc must be a vector or [H, n] tensor, got a scalar")
        return int(learnable_abc.shape[-1])
    return len(learnable_abc)


def _normalize_abc(
    learnable_abc: Union[Tensor, Sequence[float]],
    H: int,
    n_coeff: int,
    device: torch.device,
) -> Tensor:
    if torch.is_tensor(learnable_abc):
        t = learnable_abc.detach().to(device=device, dtype=torch.float32)
    else:
        t = torch.tensor(list(learnable_abc), device=device, dtype=torch.float32)
    if t.numel() == n_coeff:
        t = t.reshape(1, n_coeff).expand(H, n_coeff).contiguous()
    elif t.reshape(-1).numel() == H * n_coeff:
        t = t.reshape(H, n_coeff).contiguous()
    else:
        raise ValueError(
            f"learnable_abc must be [{n_coeff}] or [H, {n_coeff}] with H={H}, got {tuple(t.shape)}"
        )
    return t


def _as_bthd(x: Optional[Tensor], name: str) -> Optional[Tensor]:
    if x is None:
        return None
    if x.dim() == 2:
        return x[None, ...]
    if x.dim() == 3:
        return x
    raise ValueError(f"{name} must have 2/3 dims, got {tuple(x.shape)}")


@triton.jit(do_not_specialize=["T"])
def phi_kkt_decoding_kernel(
    q_ptr,
    k_ptr,
    v_ptr,
    alpha_ptr,
    g_ptr,
    gk_ptr,
    abc_ptr,
    o_ptr,
    prev_h_kk_ptr,
    prev_h_kv_ptr,
    curr_h_kk_ptr,
    curr_h_kv_ptr,
    T,
    scale,
    H: tl.constexpr,
    D: tl.constexpr,
    BD: tl.constexpr,
    N_COEFF: tl.constexpr,
    USE_G: tl.constexpr,
    USE_GK: tl.constexpr,
):
    b_id = tl.program_id(0)
    h_id = tl.program_id(1)

    o_d = tl.arange(0, BD)
    mask_d = o_d < D
    mask_dd = mask_d[:, None] & mask_d[None, :]

    state_off = (b_id * H + h_id).to(tl.int64) * D * D
    p_hkk = prev_h_kk_ptr + state_off + o_d[:, None] * D + o_d[None, :]
    p_hkv = prev_h_kv_ptr + state_off + o_d[:, None] * D + o_d[None, :]
    b_h_kk = tl.load(p_hkk, mask=mask_dd, other=0).to(tl.float32)
    b_h_kv = tl.load(p_hkv, mask=mask_dd, other=0).to(tl.float32)

    coeff_a = tl.load(abc_ptr + h_id * N_COEFF + 0).to(tl.float32)
    coeff_b = tl.load(abc_ptr + h_id * N_COEFF + 1).to(tl.float32)
    coeff_c = tl.load(abc_ptr + h_id * N_COEFF + 2).to(tl.float32)
    coeff_d = 0.0
    if N_COEFF == 4:
        coeff_d = tl.load(abc_ptr + h_id * N_COEFF + 3).to(tl.float32)

    for t in range(0, T):
        vec_off = ((b_id * T + t) * H + h_id) * D
        scalar_off = (b_id * T + t) * H + h_id

        b_q = tl.load(q_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32)
        b_k = tl.load(k_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32)
        b_v = tl.load(v_ptr + vec_off + o_d, mask=mask_d, other=0).to(tl.float32)
        b_alpha = tl.load(alpha_ptr + scalar_off).to(tl.float32)

        if USE_GK:
            b_gkk = exp(tl.load(gk_ptr + scalar_off).to(tl.float32))
        else:
            b_gkk = 1.0
        if USE_G:
            b_g = exp(tl.load(g_ptr + scalar_off).to(tl.float32))
        else:
            b_g = 1.0

        b_h_kk = b_h_kk * b_gkk + b_k[:, None] * b_k[None, :]
        fro = tl.sqrt(tl.sum(b_h_kk * b_h_kk)) + 1e-12

        o1 = tl.sum(b_h_kk * b_q[:, None], axis=0) / fro
        o2 = tl.sum(b_h_kk * o1[:, None], axis=0) / fro
        q_poly = coeff_a * b_q + coeff_b * o1 + coeff_c * o2
        if N_COEFF == 4:
            o3 = tl.sum(b_h_kk * o2[:, None], axis=0) / fro
            q_poly = q_poly + coeff_d * o3

        q_mix = b_q + b_alpha * (q_poly - b_q)
        b_h_kv = b_h_kv * b_g + b_k[:, None] * b_v[None, :]
        b_o = scale * tl.sum(b_h_kv * q_mix[:, None], axis=0)
        tl.store(o_ptr + vec_off + o_d, b_o.to(o_ptr.dtype.element_ty), mask=mask_d)

    p_hkk_out = curr_h_kk_ptr + state_off + o_d[:, None] * D + o_d[None, :]
    p_hkv_out = curr_h_kv_ptr + state_off + o_d[:, None] * D + o_d[None, :]
    tl.store(p_hkk_out, b_h_kk.to(p_hkk_out.dtype.element_ty), mask=mask_dd)
    tl.store(p_hkv_out, b_h_kv.to(p_hkv_out.dtype.element_ty), mask=mask_dd)


def _prepare_decode_inputs(
    q: Tensor,
    k: Tensor,
    v: Tensor,
    alpha: Tensor,
    g: Optional[Tensor],
    gk: Optional[Tensor],
    prev_h_kk: Optional[Tensor],
    prev_h_kv: Optional[Tensor],
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Optional[Tensor], Optional[Tensor], Tensor, Tensor]:
    if q.dim() < 4:
        q = q[None, ...]
        k = k[None, ...]
        v = v[None, ...]
    alpha = _as_bthd(alpha, "alpha")
    g = _as_bthd(g, "g")
    gk = _as_bthd(gk, "gk")

    B, T, H, D = q.shape
    if prev_h_kk is None:
        prev_h_kk = q.new_zeros(B, H, D, D, dtype=torch.float32)
    else:
        if prev_h_kk.dim() == 3:
            prev_h_kk = prev_h_kk.unsqueeze(0)
        prev_h_kk = prev_h_kk.contiguous()
        if prev_h_kk.shape[0] == 1 and B > 1:
            prev_h_kk = prev_h_kk.expand(B, -1, -1, -1).contiguous()
    if prev_h_kv is None:
        prev_h_kv = q.new_zeros(B, H, D, D, dtype=torch.float32)
    else:
        if prev_h_kv.dim() == 3:
            prev_h_kv = prev_h_kv.unsqueeze(0)
        prev_h_kv = prev_h_kv.contiguous()
        if prev_h_kv.shape[0] == 1 and B > 1:
            prev_h_kv = prev_h_kv.expand(B, -1, -1, -1).contiguous()
    return q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv


@input_guard
def phi_kkt_decoding_one_step(
    q: Tensor,
    k: Tensor,
    v: Tensor,
    alpha: Tensor,
    g: Tensor,
    gk: Tensor,
    gla_scale,
    learnable_abc: Tensor,
    prev_h_kk: Tensor,
    prev_h_kv: Tensor,
) -> Tuple[Tensor, Tensor, Tensor]:
    """
    Fused single-step (or short-T) Sigma GKA inference with cached H_kk / H_kv.

        H_t = exp(g_t) H_{t-1} + k_t k_t^T
        q_t_out = a q_t + b (q_t H_t)/F + c (q_t H_t^2)/F^2  [+ d (q_t H_t^3)/F^3]

    Args:
        q, k, v: [B, T, H, D] or [T, H, D]
        alpha: [B, T, H] or [T, H]
        g, gk: [B, T, H] or [T, H]
        prev_h_kk: previous key-key state [B, H, D, D] or [H, D, D]
        prev_h_kv: previous key-value state [B, H, D, D] or [H, D, D]
    """
    q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv = _prepare_decode_inputs(
        q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv
    )
    B, T, H, D = q.shape
    n_coeff = _coeff_last_dim(learnable_abc)
    if n_coeff not in (3, 4):
        raise ValueError(
            f"learnable_abc last dim must be 3 (abc) or 4 (abcd), got {n_coeff}"
        )
    abc = _normalize_abc(learnable_abc, H, n_coeff, q.device)
    if gla_scale is None:
        gla_scale = D ** -0.5

    dummy = q.new_empty(1)
    g_ptr = g if g is not None else dummy
    gk_ptr = gk if gk is not None else dummy

    o = torch.empty_like(q)
    curr_h_kk = torch.empty_like(prev_h_kk)
    curr_h_kv = torch.empty_like(prev_h_kv)
    BD = max(triton.next_power_of_2(D), 16)
    if BD > 256:
        raise ValueError(f"fused decoding supports head dim <= 256, got D={D}")

    phi_kkt_decoding_kernel[(B, H)](
        q,
        k,
        v,
        alpha,
        g_ptr,
        gk_ptr,
        abc,
        o,
        prev_h_kk,
        prev_h_kv,
        curr_h_kk,
        curr_h_kv,
        T,
        float(gla_scale),
        H=H,
        D=D,
        BD=BD,
        N_COEFF=n_coeff,
        USE_G=g is not None,
        USE_GK=gk is not None,
        num_warps=4 if BD <= 64 else 8,
        num_stages=2,
    )
    return o, curr_h_kk, curr_h_kv


def phi_kkt_decoding_one_step_ref(
    q: Tensor,
    k: Tensor,
    v: Tensor,
    alpha: Tensor,
    g: Tensor,
    gk: Tensor,
    gla_scale,
    learnable_abc: Tensor,
    prev_h_kk: Tensor,
    prev_h_kv: Tensor,
) -> Tuple[Tensor, Tensor, Tensor]:
    """PyTorch + fused-recurrent Simple-GLA reference used for correctness checks."""
    q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv = _prepare_decode_inputs(
        q, k, v, alpha, g, gk, prev_h_kk, prev_h_kv
    )
    n_coeff = _coeff_last_dim(learnable_abc)
    if n_coeff == 3:
        solver = test_q_kkt_solve_approx_abc
    elif n_coeff == 4:
        solver = test_q_kkt_solve_approx_abcd
    else:
        raise ValueError(
            f"learnable_abc last dim must be 3 (abc) or 4 (abcd), got {n_coeff}"
        )
    q_, h_kk, _ = solver(
        q,
        k,
        gk,
        h0=prev_h_kk,
        learnable_abc=learnable_abc,
    )
    q_mix = q + alpha[..., None] * (q_ - q)
    o, h_kv = fused_recurrent_simple_gla(
        q=q_mix,
        k=k,
        v=v,
        scale=gla_scale,
        g=g,
        initial_state=prev_h_kv,
        output_final_state=True,
    )
    return o, h_kk, h_kv