File size: 5,092 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
"""
Fused Phi-KKT + Simple-GLA for Sigma GKA training.

Same math as ``phi_kkt_approx.phi_kkt_solve_gla``, but KKT apply, alpha mix,
and chunk Simple-GLA share one ``autograd.Function`` (GDN-style):

- ``k`` / cumsum gates are saved once.
- Mixed query is reconstructed in backward, not stored.
- GLA recurrent state ``h_kv`` and chunk-level ``h_kk`` are recomputed, not stored.
- ``output_final_state`` defaults to False so training does not materialize
  ``H_T`` / ``U_T``.
"""
from typing import Optional, Sequence, Tuple, Union

import torch
from torch import Tensor

from fla.ops.simple_gla import fused_recurrent_simple_gla

from .q_kkt_solve_abc import q_kkt_solve_approx as q_kkt_solve_approx_abc
from .q_kkt_solve_abcd import q_kkt_solve_approx as q_kkt_solve_approx_abcd
from ..phi_kkt_approx.q_kkt_solve_abc import (
    test_q_kkt_solve_approx as test_q_kkt_solve_approx_abc,
)
from ..phi_kkt_approx.q_kkt_solve_abc_3 import (
    test_q_kkt_solve_approx as test_q_kkt_solve_approx_abcd,
)


def _coeff_last_dim(learnable_abc: Union[Tensor, Sequence[float]]) -> int:
    """Last dim of polynomial coefficients: 3 = abc, 4 = abcd."""
    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)


@torch.compiler.disable
def phi_kkt_solve_gla(
    q: Tensor,
    k: Tensor,
    v: Tensor,
    alpha: Tensor,
    g: Tensor,
    gk: Tensor,
    gla_scale,
    learnable_abc: torch.Tensor = torch.tensor([1.0, -0.5, 0.375]),
    chunk_size: int = 64,
    h0_kk: Optional[Tensor] = None,
    h0_kv: Optional[Tensor] = None,
    output_final_state: bool = False,
) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
    """
    Fused Phi-KKT + GLA for parallel training.

    Solves q phi(k^T k) with phi(x) = x^(-1/2) (abc or abcd polynomial),
    mixes with alpha, then runs chunk Simple-GLA — all in one autograd node.

    Args:
        q: Query tensor with shape [B, L, H, D]
        k: Key tensor with shape [B, L, H, D]
        v: Value tensor with shape [B, L, H, D]
        alpha: Mixing coefficient [B, L, H]. q_new = (1-α) q + α x
        g: Forgetting gate for key-value state [B, L, H]
        gk: Forgetting gate for key-key covariance [B, L, H]
        gla_scale: Scaling factor for GLA, typically head_dim^(-0.5)
        learnable_abc: Polynomial coefficients, last dim 3 (abc) or 4 (abcd)
        chunk_size: Chunk size shared by KKT and GLA. Defaults to 64
        h0_kk: Optional initial H_kk [B, H, D, D]
        h0_kv: Optional initial H_kv [B, H, D, D]
        output_final_state: If True, return H_T and U_T. Defaults to False.

    Returns:
        o: Output tensor [B, L, H, D]
        kk_final: Final H_T [B, H, D, D], or None
        kv_final: Final GLA state [B, H, D, D], or None
    """
    n_coeff = _coeff_last_dim(learnable_abc)
    if n_coeff == 3:
        solver = q_kkt_solve_approx_abc
    elif n_coeff == 4:
        solver = q_kkt_solve_approx_abcd
    else:
        raise ValueError(
            f"learnable_abc last dim must be 3 (abc) or 4 (abcd), got {n_coeff}"
        )

    o, kk_final, kv_final = solver.apply(
        k,
        q,
        v,
        alpha,
        g,
        gk,
        chunk_size,
        learnable_abc,
        gla_scale,
        h0_kk,
        h0_kv,
        output_final_state,
    )
    return o, kk_final, kv_final


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]:
    """
    Single-step Sigma GKA inference with cached H_kk / H_kv.

    Token-by-token decoding is not fused; it reuses the same reference
    recurrence as ``phi_kkt_approx.phi_kkt_decoding_one_step``.
    """
    if q.dim() < 4:
        q = q[None, ...]
        k = k[None, ...]
        v = v[None, ...]
    if alpha is not None and alpha.dim() == 2:
        alpha = alpha[None, ...]
    if g is not None and g.dim() == 2:
        g = g[None, ...]
    if gk is not None and gk.dim() == 2:
        gk = gk[None, ...]

    if prev_h_kv is not None and prev_h_kv.dim() == 3:
        prev_h_kv = prev_h_kv.unsqueeze(0)
    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_, states, _ = solver(
        q,
        k,
        gk,
        h0=prev_h_kk,
        learnable_abc=learnable_abc,
    )
    h_kk = states
    q = q + alpha[..., None] * (q_ - q)
    o, h_kv = fused_recurrent_simple_gla(
        q=q,
        k=k,
        v=v,
        scale=gla_scale,
        g=g,
        initial_state=prev_h_kv,
        output_final_state=True,
    )
    return o, h_kk, h_kv