AI/ML Test-Time Training Fast Weights Sequence Modeling PyTorch

Test-Time Training (TTT) & Fast-Weight RNNs: Updating an MLP Hidden State via Gradient Descent on Every Token


In State Space Duality (SSD) & Hybrid Mamba-2, we saw how linear State Space Models compress an arbitrary history into a fixed-size matrix state $h_t \in \mathbb{R}^{N \times P}$ with $O(1)$ inference memory. Yet linear compression hits an expressiveness ceiling past $16\text{k}$ context: once a linear matrix is saturated, recalling nuanced multi-hop facts from early in the prompt degrades compared to full quadratic self-attention.

Test-Time Training (TTT) Layers (Sun et al., 2024, arXiv:2407.04620) break this trade-off with a deceptively simple insight: make the RNN hidden state $W_t$ a machine learning model itself, and make the state-transition recurrence a step of self-supervised gradient descent performed at test time on every incoming token $x_t$. By upgrading the hidden state from a linear matrix (TTT-Linear) to a two-layer neural network (TTT-MLP) and deriving a parallel mini-batch dual form, TTT layers achieve linear $O(T)$ complexity while continuing to lower perplexity well beyond $32\text{k}$ context.


0. From Linear State Recurrence to Self-Supervised Fast Weights

For each incoming token embedding $x_t \in \mathbb{R}^d$, a TTT layer computes three learned projections – a training view $K_t = \theta_K x_t$, a reconstruction target $V_t = \theta_V x_t$, and a test query $Q_t = \theta_Q x_t$ – then updates the inner fast-weight model $f(\cdot; W_t)$ by taking one gradient step on the self-supervised loss $\ell(W; x_t) = \frac{1}{2}\|f(K_t; W) - V_t\|_2^2$:

TTT-Linear Primal Update vs. Parallel Mini-Batch Dual Form (Sun et al., 2024)
$$\text{Inner Fast-Weight Update:}\quad W_t = W_{t-1} - \eta_t \nabla_W \ell(W_{t-1}; x_t), \qquad z_t = f(Q_t; W_t)$$ $$\text{Mini-Batch Dual Form (for } f(x; W) = x W \text{ over chunk } t = 1..b\text{):}\quad G_j = K_j W_0 - V_j$$ $$Z_{1:b} = Q_{1:b} W_0 - \underbrace{\Bigl(\mathrm{tril}\bigl(Q_{1:b} K_{1:b}^\top\bigr) \odot \eta\Bigr)}_{\text{Causal Attention-Like Matrix } M \in \mathbb{R}^{b \times b}} G_{1:b}, \qquad W_b = W_0 - \eta K_{1:b}^\top G_{1:b}$$

Look closely at the dual form: instead of materializing $b$ separate $d \times d$ weight matrices $W_1, \dots, W_b$ in HBM inside a sequential loop, computing $Z_{1:b}$ across a mini-batch of $b = 16\text{–}64$ tokens reduces to pure Tensor Core GEMMs – over $5\times$ faster on GPUs and TPUs!

1. Inner Loop (Runs at Test Time per Token) Fast weights W_t compress context via online SGD ℓ(W; x_t) = ½‖f(K_t)−V_t‖² Self-supervised view W_t ← W_{t−1} − η∇ℓ Output z_t = f(Q_t; W_t) TTT-Linear = Matrix State | TTT-MLP = Nonlinear 2-Layer Neural State 2. Outer Loop (Pretraining via Meta-Learning) Backprop through inner SGD learns (θ_K, θ_V, θ_Q, W_0, η) Parallel Dual Form Inside Chunk (b = 16..64) Z = Q W₀ − η · tril(Q K^T)(K W₀ − V) → 5× Faster GEMMs Zero intermediate W_t tensors materialized in HBM inside chunk!
Figure 1: Bi-level architecture of Test-Time Training (TTT) layers. The inner loop adapts fast weights $W_t$ at inference time, while the outer loop meta-learns the initial state $W_0$ and projections $(\theta_K, \theta_V, \theta_Q)$ via the parallel dual form.
Two Systems Footguns When Implementing TTT-Linear and TTT-MLP: (1) Inner-Loop Stability Requires LayerNorm + Residual inside $f(\cdot; W)$: Without wrapping the inner fast-weight model as $f(x; W) = x + \mathrm{LN}(f_{\text{inner}}(x; W))$, a single outlier token gradient $\nabla_W \ell$ can blow up $W_t$ mid-sequence during 32k-token rollouts. (2) Token-Dependent Learning Rate $\eta_t = \eta_{\text{base}} \sigma(\theta_{\text{lr}} \cdot x_t)$: Just like Mamba's selective $\Delta_t$, making the inner SGD step size $\eta_t$ input-dependent lets the model ignore filler tokens ($\eta_t \to 0$) and commit high-entropy facts ($\eta_t \to \eta_{\text{base}}$) to fast weights.

1. Runnable PyTorch Reference: TTT-Linear Primal Loop vs. Parallel Dual Form

The self-contained PyTorch snippet below proves that the sequential mini-batch primal update (evaluating gradients at $W_0$) and the parallel Tensor-Core dual matrix form match to $10^{-16}$ floating-point precision:

💻 Python: TTT-Linear Primal Recurrence vs. Parallel Mini-Batch Dual FormPyTorch
import math
import torch

def ttt_linear_primal(Q: torch.Tensor, K: torch.Tensor, V: torch.Tensor, W0: torch.Tensor, eta: float) -> tuple[torch.Tensor, torch.Tensor]:
    """Sequential inner-loop gradient descent over chunk [b, d] (Sun et al., arXiv:2407.04620)."""
    b, d = Q.shape
    G_batch = K @ W0 - V  # Mini-batch gradient evaluated at chunk-start fast weights W0
    W_curr = W0.clone()
    Z_out = torch.zeros(b, d, dtype=Q.dtype, device=Q.device)
    for t in range(b):
        W_curr = W_curr - eta * torch.outer(K[t], G_batch[t])
        Z_out[t] = Q[t] @ W_curr
    return Z_out, W_curr

def ttt_linear_dual(Q: torch.Tensor, K: torch.Tensor, V: torch.Tensor, W0: torch.Tensor, eta: float) -> tuple[torch.Tensor, torch.Tensor]:
    """Parallel Tensor-Core dual form: zero intermediate W_t matrices materialized!"""
    G_batch = K @ W0 - V
    M_causal = torch.tril(Q @ K.T)              # [b, b] causal inner-product matrix
    Z_out = Q @ W0 - eta * (M_causal @ G_batch) # [b, d] all chunk outputs in one GEMM!
    W_end = W0 - eta * (K.T @ G_batch)          # [d, d] final fast-weight state for next chunk
    return Z_out, W_end

if __name__ == "__main__":
    torch.manual_seed(42)
    b, d, eta = 16, 12, 0.05
    W0 = torch.randn(d, d, dtype=torch.float64) * 0.1
    K = torch.randn(b, d, dtype=torch.float64) / math.sqrt(d)
    V = torch.randn(b, d, dtype=torch.float64) / math.sqrt(d)
    Q = torch.randn(b, d, dtype=torch.float64) / math.sqrt(d)

    Z_p, W_p = ttt_linear_primal(Q, K, V, W0, eta)
    Z_d, W_d = ttt_linear_dual(Q, K, V, W0, eta)
    print(f"[PASS] TTT-Linear Output Primal vs Dual Max Diff : {(Z_p - Z_d).abs().max().item():.2e}")
    print(f"[PASS] Final Fast-Weight State W_b Max Diff      : {(W_p - W_d).abs().max().item():.2e}")
# Output:
# [PASS] TTT-Linear Output Primal vs Dual Max Diff : 2.78e-17
# [PASS] Final Fast-Weight State W_b Max Diff      : 5.55e-17

2. Sequence Memory Mechanisms: Head-to-Head

Layer Type Full Self-Attention Mamba-2 SSD (Previous Post) Test-Time Training (TTT-MLP, arXiv:2407.04620)
Hidden State Representation Uncompressed growing KV-cache ($O(T)$) Fixed linear matrix $h_t \in \mathbb{R}^{N \times P}$ Learnable 2-layer MLP fast weights $(W_{1,t}, W_{2,t})$
State Update Rule Append $(k_t, v_t)$ to memory Linear decay $a_t h_{t-1} + b_t x_t^\top$ Online self-supervised SGD $W_{t-1} - \eta_t \nabla \ell(W_{t-1}; x_t)$
Long-Context (>16k) Scaling Strongest recall; quadratic $O(T^2)$ cost Perplexity plateaus past 16k without hybrid GQA Continues decreasing perplexity at $O(T)$ linear cost