File size: 3,414 Bytes
639d0c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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 .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.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_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

# phi_kkt_decoding_one_step is the fused Triton kernel from phi_kkt_approx.decoding_one_step.