from typing import Sequence, Tuple, Union import torch from torch import Tensor from fla.ops.simple_gla import chunk_simple_gla from .q_kkt_solve_abcd_fast_2 import q_kkt_solve_approx as q_kkt_solve_approx_abcd from .q_kkt_solve_abc_fast_2 import q_kkt_solve_approx as q_kkt_solve_approx_abc from .decoding_one_step import phi_kkt_decoding_one_step # noqa: F401 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( k, q, gk, chunk_size, learnable_abc, ): """ Solve q phi(k^T k) where phi(x) = x^(-1/2). Dispatches by coefficient count: 3 (abc): x = a q + b (q@H)/F + c (q@H^2)/F^2 4 (abcd): x = a q + b (q@H)/F + c (q@H^2)/F^2 + d (q@H^3)/F^3 Returns: x: Solution tensor with shape [B, L, H, D] kk_final: Final key-key covariance H_T with shape [B, H, D, D] """ 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}" ) x, kk_final = solver.apply( k, q, gk, chunk_size, learnable_abc, ) return x, kk_final 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, ) -> Tuple[Tensor, Tensor, Tensor]: """ Phi-KKT solver for parallel training. Solves the Phi-KKT problem at each timestep, solve q phi(k^T k) where phi(x) = x^(-1/2). then computes output via GLA recurrence. Processes entire sequences in parallel. 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 with shape [B, L, H]. Controls interpolation: q_new = q + α·(x_t - q) g: Forgetting gate for key-value state with shape [B, L, H] gk: Forgetting gate for key-key covariance with shape [B, L, H] gla_scale: Scaling factor for GLA, typically head_dim^(-0.5) Returns: o: Output tensor with shape [B, L, H, D] kk_final: Final key-key covariance (H_T in the regression problem) with shape [B, H, D, D], or None if num_iter=0. kv_final: Final key-value state from GLA with shape [B, H, D, D] Notes: For single-step autoregressive inference, use phi_kkt_decoding_one_step instead. """ # q_ solves (H_t/||H_t||_F + I)^(-1/2) · q_ = q_t q_, kk_final = phi_kkt_solve( k, q, gk, chunk_size, learnable_abc, ) q = q + alpha[..., None] * (q_ - q) # Equivalent to ⍺q_ + (1-⍺)q o, kv_final = chunk_simple_gla( q=q, k=k, v=v, scale=gla_scale, g=g, output_final_state=True ) return o, kk_final, kv_final