""" 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