""" GKA Chebyshev-Sqrt Solver Implementation. This module implements the core solving routines for the GKA layer, which uses ridge regression over the entire sequence history to compute optimal states. Core Algorithm: The GKA layer finds an optimal state matrix, S_t, at each timestep that minimizes a ridge regression objective over the entire history: S_t = argmin_S { λ·||S||²_F + Σ(i=1 to t) η_i·||S·k_i - v_i||² } where: - S ∈ ℝ^(D×D) is a linear map that should satisfy S·k_i ≈ v_i for all past tokens - λ is the ridge regularization strength (prevents overfitting, ensures stability) - η_i are exponentially decaying weights controlled by forgetting gates Unlike standard SSMs that update their state based only on the current token, this formulation considers the entire past, making it optimal in the Kalman Filter sense. Mathematical Derivation: The optimal state has closed form: S_t = U_t · (H_t + λI)^(-1) where: U_t = Σ(i=1 to t) η_i v_i k_i^T (cumulative value-key outer products) H_t = Σ(i=1 to t) η_i k_i k_i^T (cumulative key-key covariance, Gram matrix) The output is computed as: y_t = S_t · q_t = U_t · (H_t + λI)^(-1) · q_t = U_t · x_t where x_t solves the ridge regression problem: (H_t + λI) · x = q_t This x_t represents q_t transformed by the inverse covariance of all past keys, accounting for correlations between keys rather than just individual similarities. Motivation — Singular Value Monotonicity: The original formulation (H_t + λI)^(-1) does NOT preserve monotonicity of the singular values as new keys are absorbed into H_t. Because H_t grows by rank-1 updates k_i k_i^T, its eigenvalues (hence singular values, since H_t is PSD) only increase, so the singular values of (H_t + λI)^(-1) only decrease — which is monotonic in the right direction. However, the *intermediate* quantities used during the Chebyshev solve (the residual polynomials and the step size derived from ||H_t||_F) do not vary monotonically, which breaks the convergence bounds the Chebyshev iteration relies on and causes instability in low precision. To restore monotonic control over the spectrum, we keep H_t and U_t unchanged but replace the (-1) power with the (-1/2) power on the inverse part. That is, instead of computing (H_t + λI)^(-1) directly, we compute M_t = (H_t + λI)^(-1/2) and recover the regression output as y_t = U_t · M_t · M_t · q_t = U_t · (H_t + λI)^(-1) · q_t The matrix square-root inverse M_t has the key property that its singular values are the reciprocal square-roots of the eigenvalues of (H_t + λI); as H_t accumulates more keys its eigenvalues grow monotonically, so the singular values of M_t shrink monotonically. This gives a well-behaved, monotone spectrum that is friendly to iterative solvers and to bfloat16 arithmetic. Brute-Force Polynomial Approximation (cf. Su's blog): Computing the matrix square-root inverse exactly is expensive. Following the brute-force approximation idea from Su's blog, we do NOT form M_t via an eigendecomposition or a Newton-Schulz iteration. Instead we approximate M_t directly with a low-order matrix polynomial in the current-step target M0 and the previous-step estimate M_{t-1}. Concretely, we maintain a running estimate M_t and update it by the recurrence M_t = c1·M_{t-1} + c2·M_{t-1}·M0 + c3·I + c4·M0 + c5·M0·M0 + c6·M0·M0·M0 where: - M0 is the per-step target square-root inverse contribution (built from the current key's rank-1 update of H_t, regularized by λ) - M_{t-1} is the running estimate carried from the previous step - I is the identity matrix - c1..c6 are scalar coefficients (fixed or learned) that fit the (-1/2) power over the expected spectrum of (H_t + λI) This is a "brute-force" approximation in the sense that we throw a generic cubic-in-M0 polynomial at the problem rather than deriving a tailored iteration; the six-term basis {M_{t-1}, M_{t-1}·M0, I, M0, M0², M0³} is rich enough to approximate the (-1/2) power on the relevant eigenvalue range while remaining cheap (only matrix-matrix products with the rank-1-derived M0 and one running state M_{t-1}). The recurrence is applied per head, in parallel across the sequence, and the resulting M_t is used to transform q_t before the GLA recurrence. Solver: The module uses Chebyshev Iteration as its underlying solver, an iterative method using accelerated gradient descent with optimal convergence properties. Preferred for numerical stability in low-precision (bfloat16) arithmetic. The Chebyshev iteration here targets the (-1/2)-power operator rather than the plain inverse, consistent with the monotonic-spectrum motivation above. Two modes are provided: - gka_chebyshev_gla: Parallel processing for entire sequences (training) - torch_decoding_one_step: Single-step processing with state management (inference) Shape Notation: We use the following variables for shape hints: B: Batch size L: Sequence length H: Number of attention heads D: Head dimension """ 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_abc_test import q_kkt_solve_approx as q_kkt_solve_approx_abc # from .q_kkt_solve_abc_3 import q_kkt_solve_approx as q_kkt_solve_approx_abcd # from .q_kkt_solve_abcd_test import q_kkt_solve_approx as q_kkt_solve_approx_abcd 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 torch_decoding_one_step instead. """ # q_ solves (H_t/||H_t||_F + I)^(-1/2) · q_ = q_t,暂时不明确abc大小设计,当然可能根据\ratio调整 q_, kk_final = phi_kkt_solve( k, q, gk, chunk_size,learnable_abc,#####maybe using learnable lambda to control the regularization strength ) 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 )####除以sqrt(d) return o, kk_final, kv_final # phi_kkt_decoding_one_step is implemented in decoding_one_step.py (fused Triton).