         Learning to (Learn at Test Time): RNNs with Expressive Hidden States


        Yu Sun * 1 Xinhao Li * 2 Karan Dalal * 3 Jiarui Xu 2 Arjun Vikram 1 Genghan Zhang 1 Yann Dubois 1
                       †                 †                   †                    †                †
           Xinlei Chen 4 Xiaolong Wang 2 Sanmi Koyejo 1 Tatsunori Hashimoto 1 Carlos Guestrin 1


                            Abstract                                  we re-evaluate these findings in Figure 1.
        Self-attention performs well in long context but              On the left, we observe that Mamba (Gu & Dao, 2023)
        has quadratic complexity. Existing RNN layers                 – one of the most popular RNNs today – scales similarly
        have linear complexity, but their performance in              to a strong Transformer, showing great progress since the
        long context is limited by the expressive power               LSTMs in 2020. However, on the right, we observe the
        of their hidden states. We present a practical                same issue with Mamba as Kaplan et al. did with LSTMs.
        framework for instantiating sequence modeling                 Tokens later in a sequence should be easier to predict on
        layers with linear complexity and expressive hid-             average, since they condition on more information. This is
        den states. The key idea is to make the hidden                indeed the case for Transformer, whose average perplexity
        state a machine learning model itself, and the up-            at each token index decreases throughout its 32k context. In
        date rule a step of self-supervised learning. Since           contrast, the same metric plateaus for Mamba after 16k.
        the hidden state is updated by training even on
                                                                      This result represents an awkward reality for existing RNNs.
        test sequences, our layers are called Test-Time
                                                                      On one hand, the main advantage of RNNs (vs. Trans-
        Training (TTT) layers. We consider two instantia-
                                                                      formers) is their linear (vs. quadratic) complexity. This
        tions: TTT-Linear and TTT-MLP, whose hidden
                                                                      asymptotic advantage is only realized in practice for long
        state is a linear model and a two-layer MLP re-
                                                                      context, which according to Figure 8 is after 8k. On the
        spectively. We evaluate our instantiations at the
                                                                      other hand, once context is long enough, existing RNNs
        scale of 125M to 1.3B parameters, comparing
                                                                      such as Mamba struggle to actually take advantage of the
        with a strong Transformer and Mamba, a modern
                                                                      extra information being conditioned on.
        RNN. Similar to Transformer, TTT-Linear and
        TTT-MLP can keep reducing perplexity by con-                  The difficulty with long context is inherent to the very na-
        ditioning on more tokens, while Mamba cannot                  ture of RNN layers: Unlike self-attention, RNN layers have
        after 16k context. TTT-MLP still faces challenges             to compress context into a hidden state of fixed size. As a
        in memory I/O, but shows larger potential in long             compression heuristic, the update rule needs to discover the
        context, pointing to a promising direction for fu-            underlying structures and relationships among thousands
        ture research.                                                or potentially millions of tokens. This need is inherently
                                                                      challenging. In this paper, we begin with the observation
                                                                      that self-supervised learning can compress a massive train-
                                                                      ing set into the weights of a model such as an LLM, which
1. Introduction                                                       often exhibits deep understanding about the semantic con-
                                                                      nections among its training data – exactly what we need
This version of the paper has been abridged to fit the page
                                                                      from a compression heuristic.
limit of ICML camera ready. Please read our arXiv version
instead: https://arxiv.org/abs/2407.04620.                            TTT layers. Motivated by this observation, we make the
                                                                      hidden state a machine learning model itself, and the update
In 2020, the OpenAI scaling law paper (Kaplan et. al (Ka-
                                                                      rule a step of self-supervised learning. Since the hidden
plan et al., 2020)) showed that LSTMs (a type of RNN)
                                                                      state is updated by training even on test sequences, these
could not scale similarly to Transformers or effectively use
                                                                      RNN layers are called Test-Time Training (TTT) layers. We
long context. Now, with modern RNNs and best practices,
                                                                      introduce two simple instantiations: TTT-Linear and TTT-
      *: Core contributors. †: Joint advising.                        MLP, where the hidden state is a linear model and a two-
1
    Stanford University 2 UC San Diego 3 UC Berkeley 4 Meta AI.       layer MLP, respectively. TTT layers can be integrated into
                                                                      any network architecture and optimized end-to-end, similar
Proceedings of the 42 nd International Conference on Machine
Learning, Vancouver, Canada. PMLR 267, 2025. Copyright 2025
                                                                      to RNNs layers and self-attention.
by the author(s).

                                                                  1
                                               Learning to (Learn at Test Time): RNNs with Expressive Hidden States


                                                                      Transformer                              11.0                          Transformer
                                                                      Mamba                                    10.5                          Mamba
                                      8.0




                                                                                      Perplexity (log scale)
             Perplexity (log scale)
                                                                      TTT-Linear                                                             TTT-Linear
                                                                      TTT-MLP                                  10.0                          TTT-MLP
                                                                                                                9.5
                                      7.0
                                                                                                                9.0
                                                                                                                8.5
                                      6.0
                                            2e+19       5e+19        1e+20    2e+20                                   128 256 512 1k 2k 4k 8k 16k 32k
                                                    FLOPs (log scale)                                                          Token index (log scale)

Figure 1. Comparing to Mamba, TTT-Linear and TTT-MLP have similar perplexity in 8k context (left) and better use of long context
(right). Evaluations follow Kaplan et al. (Kaplan et al., 2020). Left: Scaling trends on the Pile with 8k context, zoomed in between 350M
and 1.3B parameters. Right: Similar to Transformer, TTT-Linear and TTT-MLP can keep reducing perplexity by conditioning on more
tokens, while Mamba cannot after 16k context. All methods have matched training FLOPs as Mamba 1.4B.


Wall-clock time. We apply two techniques to make TTT                                              Self-attention can also be viewed from the perspective above,
layers more efficient on modern GPUs and TPUs. First,                                             except that its hidden state, commonly known as the Key-
similar to the standard practice of taking gradient steps                                         Value (KV) cache, is a list that grows linearly with t. Its
on mini-batches of sequences during regular training for                                          update rule simply appends the current KV tuple to this list,
better parallelism, we use mini-batches of tokens during                                          and the output rule scans over all tuples up to t to form
TTT. Second, we develop a dual form for operations inside                                         the attention matrix. The hidden state explicitly stores all
each TTT mini-batch. The dual form is equivalent in output                                        historic context without compression, making self-attention
to the naive implementation, but trains more than 5× faster                                       more expressive than RNN layers for long context. How-
on our TPUs.                                                                                      ever, scanning this linearly growing hidden state also takes
                                                                                                  linearly growing time per token.
Contributions and limitations. The idea of using linear
models as hidden states has already been well studied in                                          To remain both efficient and expressive in long context, we
DeltaNet (Schlag et al., 2021; Yang et al., 2024). Since our                                      need a better compression heuristic. Specifically, we need
first version was released, RNN layers with matrix (linear)                                       to compress thousands or potentially millions of tokens into
hidden states have also been further advanced in Mamba 2                                          a hidden state that can effectively capture their underlying
(Dao & Gu, 2024) and Gated DeltaNet (Yang et al., 2023).                                          structures and relationships.
Compared to this line of work, our contribution is a practi-
cal framework that can instantiate arbitrary neural networks                                       2.1. TTT as updating a hidden state
as hidden states. However, such instantiations can still re-
quire substantial wall-clock time, even after applying our                                        The process of parametric learning can be viewed as
improvements in efficiency. It remains to be seen whether                                         compressing a massive training set into the weights of a
our framework can produce instantiations that either over-                                        model. Specifically, we know that models trained with
come this limitation or offer benefits outweighing it.                                            self-supervision can capture the underlying structures and
                                                                                                  relationships behind their training data (Le, 2013) – exactly
                                                                                                  what we need from a compression heuristic.
2. Method
                                                                                                   LLMs themselves are great examples. Trained with the
All sequence modeling layers can be viewed from the per-                                           self-supervised task of next-token prediction, their weights
spective of storing historic context into a hidden state, as                                       can be viewed as a compressed form of storage for existing
shown in Figure 2. For example, RNN layers – such as                                               knowledge on the internet. By querying LLMs, we can
LSTM (Hochreiter & Schmidhuber, 1997) and Mamba (Gu                                                extract knowledge from their weights. More importantly,
& Dao, 2023) layers – compress context into a state of fixed                                       LLMs often exhibit a deep understanding of the seman-
size across time. This compression has two consequences.                                           tic connections among existing knowledge to express new
On one hand, mapping an input token xt to output token zt                                          pieces of reasoning (Achiam et al., 2023).
is efficient, because both the update rule and output rule take
constant time per token. On the other hand, the performance                                        Our key idea is to use self-supervised learning to compress
of RNN layers in long context is limited by the expressive                                         the historic context x1 , . . . , xt into a hidden state st , by
power of its hidden state st .                                                                     making the context an unlabeled dataset and the state a
                                                                                                   model. Concretely, the hidden state st is now equivalent to


                                                                                      2
                                Learning to (Learn at Test Time): RNNs with Expressive Hidden States

                             Output tokens                                            output               Output rule


                             Hidden state                  ...                        update               Update rule


                             Input tokens

                                Initial state          Update rule                             Output rule                         Cost
            Naive RNN           s0 = vector()          st = σ (θss st−1 + θsx xt )             zt = θzs st + θzx xt                O(1)
                                                                                                                               
            Self-attention      s0 = list()            st = st−1 .append(kt , vt )             zt = Vt softmax        KtT qt       O(t)
            Naive TTT           W0 = f.params()        Wt = Wt−1 − η∇ℓ(Wt−1 ; xt )             zt = f (xt ; Wt )                   O(1)

Figure 2. Top: A generic sequence modeling layer expressed as a hidden state that transitions according to an update rule. All sequence
modeling layers can be viewed as different instantiations of three components in this figure: the initial state, update rule and output rule.
Bottom: Examples of sequence modeling layers and their instantiations of the three components. Self-attention has a hidden state growing
with context, therefore growing cost per token. Both the naive RNN and TTT layer compress the growing context into a hidden state of
fixed size, therefore their cost per token stays constant.


Wt , the weights of a model f , which can be a linear model,               2.2. Training a network with TTT layers
a small neural network, or anything else. The output rule is
                                                                           The forward pass of a TTT layer also has a correspond-
simply: zt = f (xt ; Wt ). Intuitively, the output token is just
                                                                           ing backward pass. Our forward pass only consists of stan-
the prediction on xt , made by f with the updated weights
                                                                           dard differentiable operators except the gradient operator
Wt . The update rule is a step of gradient descent on some
                                                                           ∇. However, ∇ just maps one function to another, in this
self-supervised loss ℓ:
                                                                           case ℓ to ∇ℓ, and ∇ℓ is also composed of differentiable
                                                                           operators. Conceptually, calling backward on ∇ℓ means
               Wt = Wt−1 − η ∇ℓ(Wt−1 ; xt ),                     (1)       taking gradients of gradients – a well explored technique in
                                                                           meta-learning (Maclaurin et al., 2015).
with learning rate η.1 From the compression point of view,                 TTT layers have the same interface as RNN layers and self-
every heuristic needs to decide which input to remember                    attention, therefore can be replaced in any larger network
or forget. Our W remembers inputs that produce large                       architecture, which usually contains many of these sequence
gradients – intuitively, inputs that make W learn a lot.                   modeling layers. Training a network with TTT layers also
                                                                           works the same way as training any other language model,
One choice of ℓ is reconstructing xt itself. To make the
                                                                           such as a Transformer. The same data, recipe, and objec-
learning problem nontrivial, we first process xt into a cor-
                                                                           tive such as next-token prediction can be used to optimize
rupted input x̃t (details in Subsection 2.3), then optimize:
                                                                           parameters of the rest of the network.
                                                                           We refer to training the larger network as the outer loop,
               ℓ(W ; xt ) = ∥f (x̃t ; W ) − xt ∥2 .              (2)       and training W within each TTT layer as the inner loop.
                                                                           An important difference between the two nested learning
Similar to denoising autoencoders (Vincent et al., 2008),                  problems is that the inner-loop gradient ∇ℓ is taken w.r.t.
f needs to discover the correlations between dimensions                    W , the parameters of f , while the outer-loop gradient is
of xt in order to reconstruct it from partial information                  taken w.r.t the parameters of the rest of the network, which
x̃t . We discuss more sophisticated formulations of the self-              we will denote by θrest . Throughout this paper, outer-loop
supervised task in Subsection 2.3.                                         parameters are always denoted by θ with various subscripts.

As with other RNN layers and self-attention, our algorithm                 2.3. Learning a self-supervised task for TTT
that maps an input sequence x1 , . . . , xT to output sequence
z1 , . . . , zT can be programmed into the forward pass of a               Arguably the most important part of TTT is the self-
sequence modeling layer, using the hidden state, update                    supervised task, because it determines the kind of features
rule, and output rule above. Even at test time, our new layer              that W will learn from the test sequence. So how should we
still trains a different sequence of weights W1 , . . . , WT for           design this task? The final goal of TTT is for zt = f (xt ; Wt )
every input sequence. Therefore, we call it the Test-Time                  to perform well on language modeling. Instead of handcraft-
Training (TTT) layer.                                                      ing a self-supervised task from human priors, we take a
    1
                                                                           more end-to-end approach – directly optimizing the self-
      For now, consider W0 = 0. We will discuss more sophisti-             supervised task for the final goal of next-token prediction.
cated techniques for initializing W in Subsection 2.7.

                                                                       3
                               Learning to (Learn at Test Time): RNNs with Expressive Hidden States

Concretely, we learn the self-supervised task as part of the
outer loop. Starting from the naive reconstruction task in
Equation 2, we add some outer-loop parameters to make
                                                                                                                                                                                               ...
this task learnable. In Subsection 2.1, we did not specify
the corruption that produces x̃t from xt . One design is to
make it a low-rank projection x̃t = θK xt , where θK is a
learnable matrix.2 Following the terminology of multi-view
reconstruction, θK xt is called a training view.                           Figure 3. High-level computation graph of the first TTT mini-
                                                                           batch, where nodes are variables and edges are computations. The
Moreover, perhaps not all the information in xt is worth                   blue nodes are input variables, and yellow are output.
remembering, so the reconstruction label can be another
low-rank projection θV xt instead of xt . Here θV xt is called




                                                                           Perplexity (log scale)
                                                                                                    11.6                                                                      200                             Ws at end of mini-batch
the label view, where θV is also learnable. In summary, our                                                                                                                                                   Total for Ws and z1, , zT




                                                                                                                                                                  Time (ms)
                                                                                                    11.4
new self-supervised loss is:                                                                        11.2                                                                      100
                                                                                                      11
                                                      2                                                                                                                        0
           ℓ(W ; xt ) = f (θK xt ; W ) − θV xt            .     (3)                                        1   2     4   8   16   32   64 128 256 512 1024 2048
                                                                                                                   TTT mini-batch size b (log scale)
                                                                                                                                                                                    1   2     4      8   16     32   64 128 256 512 1024 2048
                                                                                                                                                                                            TTT mini-batch size b (log scale)

Since both W and various θs appear together in Equation 3,                 Figure 4. Ablations on TTT mini-batch size b, where b = 1 is
we emphasize again their difference in nature. In the inner                online GD and b = T is batch GD. We choose b = 16 for all
loop, only W is optimized, therefore written as an argument                experiments in this paper. Left: Smaller b improves perplexity
of ℓ; the θs are ”hyper-parameters” of this loss function. In              since more GD steps are taken. The perplexity of 11.09 at b = 16
the outer loop, θK , θV , θQ are optimized alongside θrest , and           corresponds to the final result of TTT-Linear in Figure 6. Right:
W is merely a hidden state, not a parameter.                               Forward time in dual form, with context length T = 2048. Total
                                                                           time (orange) can be decomposed into time for computing the W s
Lastly, the training view θK xt has fewer dimensions than xt ,             at the end of every mini-batch (blue) and time for z1 , . . . , zT .
so we can no longer use the output rule in Subsection 2.1.
The simplest solution is to create a test view θQ xt , and
change our output rule to:                                                 where Gt is the descent direction. Note that once we have
                                                                           calculated Gt for t = 1, . . . , T , we can then obtain all the
                      zt = f (θQ xt ; Wt ) .                    (4)
                                                                           Wt s through a cumsum by the second half of Equation 5.
This solution has an additional benefit. The training and                  Our naive update rule, known as online gradient descent,
label views specify the information in xt that is compressed               uses Gt = ∇l(Wt−1 ; xt ).
into Wt and propagated forward through time. The test view
                                                                           To parallelize Gt for t = 1, . . . , T , we can take all of them
specifies potentially different information that is mapped to
                                                                           w.r.t. W0 . This variant with Gt P    = ∇ℓ (W0 ; xt ) is known
the current output token zt and propagated forward through                                                          t
                                                                           as batch gradient descent, since s=1 ∇ℓ (W0 ; xs ) is the
network layers, therefore adds more flexibility to the self-
                                                                           same as the gradient w.r.t. W0 over x1 , . . . , xt as a batch.
supervised task.
                                                                           However, in batch GD, Wt is effectively only one gradient
                                                                           step away from W0 , in contrast to online GD, where Wt is
2.4. Parallelization with mini-batch TTT
                                                                           t steps away from W0 . Therefore, batch GD has a smaller
The naive TTT layer developed so far is already efficient in               effective search space, which ends up hurting performance
the number of floating point operations (FLOPs). However,                  for language modeling.
its update rule Wt = Wt−1 − η∇l(Wt−1 ; xt ) cannot be                      Our proposed solution – mini-batch gradient descent – is
parallelized, because Wt depends on Wt−1 in two places:                    shown in Figure 3. Denote the TTT batch size by b. We
before the minus sign and inside ∇l. Since ∇l contains the                 use Gt = ∇ℓ (Wt′ ; xt ), where t′ = t − mod(t, b) is the
bulk of the computation, we focus on making this second                    last timestep of the previous mini-batch (or 0 for the first
part parallel.                                                             mini-batch), so we can parallelize b gradient computations
We approach this systems challenge through concepts in                     at a time. Empirically, b controls a trade-off between speed
the TTT framework. There are many variants of gradient                     and quality, as shown in Figure 4. We chose b = 16 for all
descent (GD). Its general update rule can be expressed as:                 experiments in this paper.
                                               t
                                                                           2.5. Dual form
                                               X
           Wt = Wt−1 − η Gt = W0 − η                 Gs ,       (5)
                                               s=1
                                                                           The parallelization introduced above is necessary but not
   2
      The subscript K hints at a connection to self-attention, as we       sufficient for efficiency in wall-clock time. Modern acceler-
will establish in Subsection 2.6.                                          ators specialize in matrix-matrix multiplications, known as

                                                                       4
                            Learning to (Learn at Test Time): RNNs with Expressive Hidden States

matmuls. For example, the NVIDIA A100 GPU contains                     is O(b × d2 ) for computing Wb alone, then an additional
highly optimized units called TensorCores that can only                O(b2 ×d) for computing z1 , . . . , zb . Compared to the primal,
perform a single operation – multiplying two matrices each             the dual form sacrifices theoretical complexity for hardware
of size 16 × 16. Without enough of these matmuls, the                  utilization. In practice, d is typically a few hundred and b is
TensorCores are idle, and most of the potential for the A100           chosen to be only 16. As a consequence, wall-clock time for
is unrealized.                                                         computing z1 , . . . , zb is relatively small, as observed in the
                                                                       right panel of Figure 4. In our JAX implementation, training
Unfortunately, the TTT layer developed so far even with
                                                                       with the dual form is more than 5× faster than with primal.
mini-batch still has very few matmuls. Consider the sim-
plest case of ℓ, where θK = θV = θQ = I, for only
the first TTT mini-batch of size b. In addition, consider              2.6. Theoretical equivalences
f as a linear model. Copying Equation 2, our loss at                   In Subsection 2.1, we mentioned that f can be a linear
time t is: ℓ (W0 ; xt ) = ∥W0 xt − xt ∥2 . As discussed in             model or a neural network. In Subsection 2.4, we also
Subsection 2.4, we can parallelize the computation of:                 discussed three variants of the update rule: online GD, batch
Gt = 2(W0 xt − xt )xTt , for t = 1, . . . , b. However, we             GD, and mini-batch GD. Each of these 2 × 3 combinations
cannot compute all b of the Gt s through a single matmul.              induces a different instantiation of the TTT layer. We now
Instead, we need b outer products to compute them one by               show that among these induced instantiations, the TTT layer
one. To make matters worse, for each xt ∈ Rd , Gt is d × d,            with a linear model and batch GD is equivalent to linear
which incurs much heavier memory footprint and I/O cost                attention (Katharopoulos et al., 2020).
than xt for large d.
                                                                       Theorem 1. Consider the TTT layer with f (x) = W x as
To solve these two problems, we make a simple observa-                 the inner-loop model, batch gradient descent with η = 1/2
tion: We do not actually need to materialize G1 , . . . , Gb           as the update rule, and W0 = 0. Then, given the same input
as long as we can compute Wb at the end of the mini-                   sequence x1 , . . . , xT , the output rule defined in Equation 4
batch, and the output tokens z1 , . . . , zb (see Figure 3). Now       produces the same output sequence z1 , . . . , zT as linear
we demonstrate these computations with the simplified                  attention.
TTT-Linear case above. Denote X = [x1 , . . . , xb ], then:
Wb = W0 −2η(W0 X −X)X T . So Wb can be conveniently                    Proof. By definition of ℓ in Equation 3, ∇ℓ (W0 ; xt ) =
computed with a matmul. To compute Z = [z1 , . . . , zb ],             −2(θV xt )(θK xt )T . By definition of batch GD: Wt =
                                                                       P  t                   T
we know that:                                                             s=1 (θV xs )(θK xs ) . Plugging Wt into the output rule
                                t                                      in Equation 4, we   Pt obtain the output      token: zt =
                                                                                                                  T
                                                                       f (θQ xt ; Wt ) =      s=1 (θV xs )(θK xs ) (θQ xt ), which is
                                X
 zt = f (xt ; Wt ) = W0 xt − 2η   (W0 xs − xs )xTs xt . (6)
                                  s=1                                  the definition of linear attention.
              Pt
Denote δt = s=1 (W0 xs − xs )xTs xt and the matrix ∆ =
[δ1 , . . . , δb ]. We can derive that:                                In Table 1, we first empirically verify the equivalence above
                                                                       with an improved implementation of linear attention. Then,
                   ∆ = (W0 X − X) mask X T X ,
                                            
                                                    (7)
                                                                       to illustrate the contribution of each of our components (in-
where mask is the upper triangular mask with zeros (similar            cluding some that will be introduced in the next subsection),
to the attention mask, but with zeros instead of infinities),          we add them row by row to the TTT layer that is equivalent
and the term W0 X − X can be reused from the computa-                  to linear attention, and ultimately obtain our proposed in-
tion of Wb . Now ∆ is also conveniently computed with                  stantiation called TTT-Linear. The change from batch GD
matmuls. Plugging ∆ back into Equation 6, we obtain                    to mini-batch GD contributes the most improvement by a
Z = W0 X − 2η∆.                                                        large margin.
We call this procedure the dual form, in contrast to the               While the space of models × optimizers is already large,
primal form before this subsection, where the Gs and W s               machine learning is much richer than optimizing the parame-
are explicitly materialized. As discussed, the two forms are           ters Wt of a model f . There are also nonparametric learners,
equivalent in output. The terminology of primal and dual               such as nearest neighbors, support vector machines (SVMs),
follows prior work that has explored similar mathematical              and kernel ridge regression. By definition, nonparametric
formulations outside of TTT (Irie et al., 2022; Bishop &               learners do not have parameters Wt , and instead directly
Nasrabadi, 2006; Rosenblatt, 1958). In Appendix A, we                  uses training data x1 , . . . , xt . Hence we use the notation
show that the dual form still works when f is a neural                 f (x; x1 , . . . , xt ). We now show that for a particular non-
network with nonlinear layers.                                         parametric learner, the induced TTT layer is equivalent to
                                                                       self-attention.
Time complexity of the primal form within a TTT mini-
batch is O(b × d2 ). Time complexity of the dual form                  Theorem 2. Consider the TTT layer with the Nadaraya-

                                                                   5
                                  Learning to (Learn at Test Time): RNNs with Expressive Hidden States

                   Sequence modeling layers                                       Configuration                                    Ppl.   Diff.
                                                                                  Linear attention (Katharopoulos et al., 2020)   15.91     -
                 RNN layers               TTT layers                              Linear attn. improved                           15.23   −0.68
              • Mamba        w/ parametric        w/ nonparametric                TTT equivalence                                 15.23     0
              • RWKV           learners               learners
                            Details in Figure 9    • Self-attention
                                                                                  + learnable W0                                  15.27   +0.04
              • LSTM
                                                   •…                             + LN and residual in f                          14.05   −1.22
              •…
                                                                                  + mini-batch TTT                                12.35   −1.70
                                                                                  + learnable η                                   11.99   −0.36
Figure 5. RNN layers and TTT layers are both subsets of                           + Mamba backbone                                11.09   −0.90
sequence modeling layers. RNN layers have a hidden state that
is fixed in size across time. TTT layers with parametric learn-                 Table 1. Ablations on improving from linear attention. All models
ers are also RNN layers, since their hidden state is also fixed in              here have 125M parameters, and are trained according to the recipe
size. TTT layers with nonparametric learners can represent self-                in Subsection 3.1. The last row, with perplexity 11.09, is the final
attention, as discussed in Subsection 2.6.                                      result of TTT-Linear in Figure 6. Starting from the equivalence
                                                                                discussed in Subsection 2.6, learnable W0 hurts slightly, but the
                                                                                rows below cannot train stably without it. The biggest improve-
Watson estimator (Bierens, 1988; Cai, 2001), defined as:                        ment comes from mini-batch TTT (changing from b = T = 2048
                                              t                                 to b = 16). The second comes from instantiating the inner model
                                   1         X                                  f with LN and residual connection.
  f (x; x1 , . . . , xt ) = Pt                   κ(x, xs ) ys , (8)
                               s=1 κ(x, xs ) s=1

where ys = θV xs , and                                                          adds a negligible amount of parameters comparing to the
                        ′                     (θK x)T θQ x′                     reconstruction views θK , θQ , θV , because both its input and
               κ (x, x ; θK , θQ ) ∝ e                                (9)
                                                                                output are low dimensional. Empirically, we observe that
is a kernel with bandwidth hyper-parameters θK and θQ .                         learning W0 significantly improves training stability.
Then given the same input sequence x1 , . . . , xT , the out-                   Learnable η. The learning rate is usually the most important
put rule defined in Equation 4 produces the same output                         hyper-parameter for gradient descent, so we experiment
sequence z1 , . . . , zT as self-attention.                                     with learning the inner-loop learning rate η in Equation 5
Proof. Plugging ys and κ above into Equation 8 gives us                         as part of the outer loop. We make η a function of the
the definition of self-attention.                                               input token (therefore different across time) for additional
                                                                                flexibility. Concretely, we design η(x) = ηbase σ(θlr · x),
Appendix B contains a detailed explanation of the Nadaraya-                     where the learnable vector θlr is an outer-loop parameter,
Watson estimator and kernel κ above. In contrast to Theo-                       σ is the sigmoid function, and the scalar ηbase is the base
rem 1, Theorem 2 does not produce a different implementa-                       learning rate, set to 1 for TTT-Linear and 0.1 for TTT-MLP.
tion from attention.                                                            Alternatively, η(x) can also be interpreted as a gate for ∇ℓ.
                                                                                Backbone architecture. The cleanest way to integrate
2.7. Implementation details                                                     any RNN layer into a larger architecture would be to di-
                                                                                rectly replace self-attention in a Transformer, known in this
Instantiations of f . We propose two variants of TTT lay-
                                                                                context as a backbone. However, existing RNNs such as
ers – TTT-Linear and TTT-MLP, differing only in their
                                                                                Mamba (Gu & Dao, 2023) and Griffin (De et al., 2024)
instantiations of f . For TTT-Linear, f lin (x) = W x, where
                                                                                all use a different backbone from Transformers. Most no-
W is square. For TTT-MLP, f MLP has two layers similar
                                                                                tably, their backbone contains temporal convolutions before
to the MLPs in Transformers. Specifically, the hidden di-
                                                                                the RNN layers, which might help collect local information
mension is 4× the input dimension, followed by a GELU
                                                                                across time. After experimenting with the Mamba backbone,
activation (Hendrycks & Gimpel, 2016). For better stability
                                                                                we find that it also improves perplexity for TTT layers, so
during TTT, f always contains a Layer Normalization (LN)
                                                                                we incorporate it into our proposed method. See Figure 9
and residual connection. That is, f (x) = x + LN(f res (x)),
                                                                                (in Appendix) for details.
where f res can be f lin or f MLP .
Learnable W0 . The TTT initialization W0 is shared                              3. Experiments
between all sequences, even though subsequent weights
W1 , . . . , WT are different for each input sequence. Instead                  We evaluate TTT-Linear and TTT-MLP by comparing with
of setting W0 = 0, we can learn it as part of the outer loop.                   two baselines – Transformer and Mamba, a modern RNN.
Since outer-loop parameters are always denoted by θs in-                        Our main codebase is based on EasyLM (Geng, 2023), an
stead of W s, we assign an alias θinit = W0 . In practice, θinit                open-source project for training and serving LLMs in JAX.

                                                                            6
                                                                    Learning to (Learn at Test Time): RNNs with Expressive Hidden States

                              Scaling trends on Pile 2k                                                  Scaling trends on Pile 8k                                                        Scaling trends on Books 2k                                                  Scaling trends on Books 32k
                                                          Transformer                                                                Transformer                                   18                               Transformer                               20                                    Transformer
                                                          Mamba                                     11                               Mamba                                                                          Mamba                                                                           Mamba
                         11                               TTT-Linear (M)                                                             TTT-Linear (M)                                                                 TTT-Linear (M)                            18                                    TTT-Linear (M)
                                                                                                                                                                                   16
                                                          TTT-MLP (M)                               10                               TTT-MLP (M)                                                                    TTT-MLP (M)                                                                     TTT-MLP (M)
                         10
Perplexity (log scale)




                                                                           Perplexity (log scale)




                                                                                                                                                          Perplexity (log scale)




                                                                                                                                                                                                                                     Perplexity (log scale)
                                                          TTT-Linear (T)                                                             TTT-Linear (T)                                                                 TTT-Linear (T)                            16                                    TTT-Linear (T)
                                                          TTT-MLP (T)                               9                                TTT-MLP (T)                                   14                               TTT-MLP (T)                                                                     TTT-MLP (T)
                         9                                                                                                                                                                                                                                    14
                                                                                                    8
                         8                                                                                                                                                         12                                                                         12
                                                                                                    7
                         7                                                                                                                                                                                                                                    10
                                                                                                                                                                                   10
                                                                                                    6                                                                                                                                                          9
                         6
                                   1019                     1020                                             1019                 1020                                                          1019                   1020                                    1018      1019                1020
                                   FLOPs (log scale)                                                          FLOPs (log scale)                                                                 FLOPs (log scale)                                                           FLOPs (log scale)



Figure 6. Evaluations for context lengths 2k and 8k on the Pile. De-                                                                                      Figure 7. Evaluations for context lengths 2k and 32k on Books.
tails in Subsection 3.1. TTT-Linear has comparable performance                                                                                            Details in Subsection 3.2. Our complete results for context lengths
as Mamba at 2k context, and better performance at 8k.                                                                                                     1k, 2k, 4k, 8k, 16k, 32k, including Transformer finetuning, are in
                                                                                                                                                          Figure 11 (in Appendix).

Datasets. Following the Mamba paper (Gu & Dao, 2023),
we perform standard experiments with 2k and 8k context                                                                                                                             former backbone performs slightly better than Mamba
lengths on the Pile (Gao et al., 2020), a popular dataset                                                                                                                          around 1.3B. A robust phenomenon we observe through-
of documents for training open-source LLMs (Black et al.,                                                                                                                          out this paper is that as context length grows longer, the
2022). However, the Pile contains few sequences of length                                                                                                                          advantage of TTT layers over Mamba widens.
greater than 8k (de Vries, 2023). To evaluate capabilities
                                                                                                                                                          • At 8k context, Transformer still has good (if not the best)
in long context, we also experiment with context lengths
                                                                                                                                                            perplexity at every model size, but its line is not competi-
ranging from 1k to 32k in 2× increments, on a subset of
                                                                                                                                                            tive because of the cost in FLOPs.
the Pile called Books3, which has been widely used to train
LLMs in long context (Liu et al., 2024).                                                                                                                  Effect of backbone. Switching the TTT layers from Mamba
Backbone architecture. As discussed in Subsection 2.7,                                                                                                    backbone into Transformer backbone has two effects. First,
Transformer and Mamba use different backbones, and TTT-                                                                                                   TTT layers with Mamba backbone perform better in our
Linear and TTT-MLP always use the Mamba backbone                                                                                                          evaluations so far. Second, with Mamba backbone, TTT-
unless noted otherwise. As an ablation study, Figure 6                                                                                                    MLP at best is only comparable to TTT-Linear; but with
and Figure 7 contain TTT layers within the Transformer                                                                                                    Transformer backbone, TTT-MLP is clearly better. We hy-
backbone. When a figure contains both the Transformer                                                                                                     pothesize that the temporal convolutions in the Mamba back-
backbone and Mamba backbone, we denote them by (T) and                                                                                                    bone help more when the sequence modeling layer has a less
(M), respectively.                                                                                                                                        expressive hidden state. The linear model is less expressive
                                                                                                                                                          than the MLP, therefore benefits more from the convolutions.
Protocols. To ensure fairness to our baselines, we strictly                                                                                               We will revisit this hypothesis in the next subsection.
follow the evaluation protocols in the Mamba paper when
possible. For each evaluation setting (e.g., dataset, context
                                                                                                                                                          3.2. Long context: Books
length, and method), we experiment with four model sizes:
125M, 350M, 760M, and 1.3B parameters. For Mamba, the                                                                                                     To evaluate capabilities in long context, we experiment with
corresponding sizes are 130M, 370M, 790M, and 1.4B, as                                                                                                    context lengths ranging from 1k to 32k in 2× increments,
Mamba does not follow the Transformer configurations. All                                                                                                 using a popular subset of the Pile called Books3. The train-
models are trained with the Chinchilla recipe described in                                                                                                ing recipe here is the same as that for Pile. From the subset
the Mamba paper and reproduced in our Appendix C.                                                                                                         of results in Figure 7, we make a few observations:
                                                                                                                                                          • At 2k context on Books, all the observations from Pile 2k
3.1. Short context: the Pile                                                                                                                                still hold, except that Mamba now performs slightly better
From Figure 6, we make a few observations:                                                                                                                  than TTT-Linear (whereas their lines roughly overlapped
                                                                                                                                                            for Pile 2k).
• At 2k context, TTT-Linear (M), Mamba, and Transformer
  have comparable performance, as the lines mostly overlap.                                                                                               • At 32k context, both TTT-Linear (M) and TTT-MLP (M)
  TTT-MLP (M) performs slightly worse under large FLOP                                                                                                      perform better than Mamba, similar to the observation
  budgets. Even though TTT-MLP has better perplexity                                                                                                        from Pile 8k. Even TTT-MLP (T) with the Transformer
  than TTT-Linear at every model size, the extra cost in                                                                                                    backbone performs slightly better than Mamba at 32k
  FLOPs offsets the advantage.                                                                                                                              context.
• At 8k context, both TTT-Linear (M) and TTT-MLP (M)                                                                                                      • TTT-MLP (T) is only slightly worse than TTT-MLP (M)
  perform significantly better than Mamba, in contrast to                                                                                                   at 1.3B scale. As discussed, it is hard to derive an em-
  the observation at 2k. Even TTT-MLP (T) with the Trans-                                                                                                   pirical scaling law due to the lack of a clean linear fit.

                                                                                                                                                      7
                                                                            Learning to (Learn at Test Time): RNNs with Expressive Hidden States

                              Forward (prefill) latency for batch size 16                                   Generate (decode) latency for batch size 512
                     3.5
                           1e 5                                                                            1e 4                                                Due to resource constraints, our experiments are written
                                  Transformer                                                                     Transformer
                     3.0
                                  Mamba                                                                6          Mamba                                        in JAX and run on TPUs. On a v5e-256 TPU pod, the
                                  TTT-Linear                                                                      TTT-Linear
Time (sec / token)




                                                                                  Time (sec / token)
                                  TTT-MLP                                                                         TTT-MLP                                      Transformer baseline takes 0.30s per iteration of training
                     2.5                                                                               4

                     2.0                                                                                                                                       at context 2k, while TTT-Linear takes 0.27s per iteration,
                                                                                                       2
                     1.5                                                                                                                                       already 10% faster without any systems optimization. How-
                            2k 4k     8k           16k
                                                Context length
                                                                            32k                            512 1k     2k            4k
                                                                                                                                Context length
                                                                                                                                                      8k       ever, Mamba (implemented in PyTorch, Triton, and CUDA)
                                                                                                                                                               can only run on GPUs, so for fair comparison, we also
Figure 8. Latency on an NVIDIA A100 GPU with 80G HBM and                                                                                                       rewrite our method into GPU kernels. We only write infer-
PCIe connections.                                                                                                                                              ence kernels for this work because the training kernel would
                                                                                                                                                               require substantial effort and cannot be used on our TPUs.
                     However, the strong trend for TTT-MLP (T) suggests that
                     the Transformer backbone might be more suitable for                                                                                       Figure 8 shows the latency of our inference kernel for for-
                     larger models and longer context beyond our evaluations.                                                                                  ward (prefill) and generate (decode). All models are 1.3B
                                                                                                                                                               (1.4B for Mamba). As expected, time per token grows lin-
We only ablate the backbones for 2k and 32k due to the cost                                                                                                    early for Transformer as the context length increases, but
of training LLMs. For future work, we believe that given                                                                                                       stays roughly constant for the other methods. Note that
TTT layers with even more expressive hidden states, the                                                                                                        our Transformer baseline is significantly faster that in the
Mamba backbone with convolutions will be unnecessary.                                                                                                          Mamba paper, because we use vLLM (Kwon et al., 2023), a
                                                                                                                                                               state-of-the-art serving system, instead of the HuggingFace
Transformer finetuning. While we have been training                                                                                                            Transformer (Wolf et al., 2019).
Transformers from scratch following the Mamba paper, in
practice this approach is rarely used for long context. The
standard practice is to train a Transformer in short context,                                                                                                  4. Related Work
then finetune in long context. To reflect this practice, we                                                                                                    4.1. Learning at Test Time
add another baseline, TF finetune, for context lengths 4k and
above. This baseline starts from the model trained (accord-                                                                                                    The idea of learning at test time has a long history in ma-
ing to the Chinchilla recipe) on Books 2k, then uses 20%                                                                                                       chine learning. One of the earliest versions of this idea is
more tokens to finetune at the designated context length,                                                                                                      called local learning (Bottou and Vapnik (Bottou & Vapnik,
following the Llama Long paper (Xiong et al., 2023). See                                                                                                       1992)): For each test input, train on its neighbors before
details of the TF finetune recipe in Appendix C.                                                                                                               making a prediction. This procedure has been effectively
                                                                                                                                                               applied to models ranging from SVMs (Zhang et al., 2006)
Experiments in Figure 1 (right). Compared to TTT-Linear,                                                                                                       to modern LLMs (Hardt & Sun, 2023). Next, we discuss
TTT-MLP with matched FLOPs performs worse at short                                                                                                             two relevant lines of work in detail: test-time training and
context but better at long context. This observation matches                                                                                                   fast weights.
our expectation that the MLP as hidden state is more ex-
pressive than the linear model: The larger capacity of a                                                                                                       4.1.1. T EST-T IME T RAINING
more expressive hidden state is well-utilized in long con-
text (therefore an advantage), but redundant in short con-                                                                                                     The core idea of Test-Time Training (TTT) is that each test
text (therefore a disadvantage in our setting with matched                                                                                                     instance defines its own learning problem, where this test in-
FLOPs). The Transformer in this figure is TF finetune,                                                                                                         stance alone is the target of generalization (Sun et al., 2020).
which is the stronger baseline in 32k context. Details of the                                                                                                  Concretely, for each test instance x, the conventional prac-
experiments in Figure 1 are included in Appendix C. Our                                                                                                        tice is to predict f (x), using a predictor f that is optimized
complete results for context lengths 1k, 2k, 4k, 8k, 16k, 32k,                                                                                                 for all training instances on average. TTT first formulates a
including TF finetune, are in Figure 11 (in Appendix).                                                                                                         learning problem defined by x, then trains a model fx on x
                                                                                                                                                               (often with f as initialization), and predicts fx (x).
3.3. Wall-clock time                                                                                                                                           Since the test instance comes without its label, the learning
LLM training and inference can be decomposed into for-                                                                                                         problem can only be formulated with a self-supervised task.
ward, backward, and generate. Prompt processing during                                                                                                         Prior work has shown that TTT with reconstruction signif-
inference, also known as prefill, is the same operation as                                                                                                     icantly improves performance especially on outliers (Gan-
forward during training, except that the intermediate acti-                                                                                                    delsman et al., 2022). Improvements become even more
vations do not need to be stored for backward. Since both                                                                                                      pronounced when testing on video frames that arrive in a
forward (during training and inference) and backward can                                                                                                       stream and TTT is autoregressive (Wang et al., 2023), as
be parallelized, we use the dual form. Generating new to-                                                                                                      ft is trained on past frames x1 , . . . , xt . The autoregressive
kens, also known as decode, is inherently sequential, so we                                                                                                    connection makes (Wang et al., 2023) most relevant to our
use the primal form.                                                                                                                                           paper. Conceptually, the biggest difference between our pa-

                                                                                                                                                           8
                            Learning to (Learn at Test Time): RNNs with Expressive Hidden States

per and prior work is that our reconstruction task is learned         improvements in efficiency. For example, TTT-MLP is
in an outer loop, instead of handcrafted with human priors.           effective in terms of FLOPs, as shown in Figure 1. But
                                                                      the additional complexity of the MLP structure increases
4.1.2. FAST W EIGHTS                                                  wall-clock time much more relative to FLOPs, as shown in
                                                                      Figure 8. It remains to be seen whether our framework can
The general idea of fast weights is to update the parameters
                                                                      produce instantiations that either overcome this limitation
of a “fast” model on only the most relevant data, as opposed
                                                                      or offer benefits outweighing it.
to the conventional practice of updating a “slow” model on
all data (Tieleman & Hinton, 2009). This idea has existed
                                                                      4.3. Learning to Learn
since the 1980s (Hinton & Plaut, 1987). The most relevant
data can be the test instance itself, therefore TTT can be            For decades, researchers have been arguing that learning to
viewed as a special case of fast weights. Compared to fast            learn, also known as meta-learning or bi-level optimization,
weights, TTT embraces the idea of formulating an explicit             should be a critical component of intelligence (Schmidhuber,
learning problem, where the test instance is the target of            1987; Bengio et al., 1990; Thrun & Pratt, 1998; Lake et al.,
generalization. Our update rule is also an explicit step of           2017). In prior work such as (Andrychowicz et al., 2016),
optimization.                                                         (Finn et al., 2017) and (Metz et al., 2018), the inner loop
The idea of fast weight programmers (FWPs) is to update the           learns from an entire dataset at a time instead of a sequence,
fast weights with a “slow” model (Schmidhuber, 1992). As              so the outer loop needs a collection of datasets or tasks. In
a modern example for language modeling, Clark et al. (Clark           short, the outer loop is “one level above” regular training.
et al., 2022) give a Transformer a final layer of fast weights,       Since it is hard to collect millions of datasets, this outer loop
whose initialization is trained as slow weights. Our inner-           is hard to scale.
loop weights W can be viewed as “fast” and outer-loop                 In contrast, for TTT, each sequence itself is a dataset and
weights θ as “slow”. Therefore, networks containing TTT               defines its own generalization problem. The inner loop is
layers can be viewed as a special case of FWPs (Kirsch &              “one level below” regular training, so our outer loop is only
Schmidhuber, 2021), similar to how TTT can be viewed as               another solution to the canonical problem of supervised
a special case of fast weights.                                       learning, instead of a new problem setting like generaliza-
Modern RNN layers such as linear attention (Katharopoulos             tion across datasets.
et al., 2020; Schlag et al., 2020) and DeltaNet (Schlag et al.,
2021; Yang et al., 2024) are inspired by the idea of FWPs.            5. Future work
Given their relevance to our work, we discuss these modern
RNN layers in detail in the next subsection.                          The search space for effective instantiations inside this
                                                                      framework is huge, and our paper has only taken a baby
                                                                      step. Fortunately, if our perspective holds, then heuristics
4.2. Modern RNN layers
                                                                      from regular training can transfer to test-time training, and
Our baseline, Mamba (Gu & Dao, 2023), is only one of                  search can be efficient. Next we outline some especially
the many recent RNN layers that inherit the linear (ma-               promising directions for future work:
trix) hidden states of linear attention (Katharopoulos et al.,
2020; Schlag et al., 2020). Some more recent examples                 • Systems optimization. Our systems optimization in Sub-
are RWKV (Peng et al., 2024), xLSTM (Beck et al., 2024),                section 3.3 has been preliminary at best, and there are
and Gated Linear Attention (GLA) (Yang et al., 2023). The               many ways to improve it. In addition, pipeline parallelism
most relevant work is DeltaNet (Schlag et al., 2021), which             through time might allow us to process long sequences of
is equivalent to TTT-Linear with inner-loop mini-batch size             millions of tokens on multiple devices together.
1, without the Layer Norm and residual connection. (Yang
et al., 2024) further improve the performance of DeltaNet             • Longer context and larger models. Constrained by our
and enable parallelized updates across tokens (in our terms,            academic resources, we have not trained with millions or
across inner loop mini-batches). Since our first version was            billions in context length, which would also require larger
released, RNN layers with matrix (linear) hidden states have            models according to Figure 12. The advantage of TTT
also been further advanced in Mamba 2 (Dao & Gu, 2024)                  layers should become more pronounced in longer context.
and Gated DeltaNet (Yang et al., 2023).
                                                                      • More ambitious instantiations of f . When context
Compared to this line of work, our contribution is a practical          length becomes longer, f would also need to be larger. For
framework that can instantiate arbitrary neural networks                video tasks and embodied agents, whose context length
as hidden states. However, such instantiations can still                can easily scale up to millions or billions, f could be a
require substantial wall-clock time, even after applying our            convolutional neural network.


                                                                  9
                           Learning to (Learn at Test Time): RNNs with Expressive Hidden States

Impact statement                                                    Bengio, Y., Bengio, S., and Cloutier, J. Learning a synaptic
                                                                      learning rule. Citeseer, 1990.
This paper presents work whose goal is to advance the field
of Machine Learning. There are many potential societal              Bierens, H. J. The nadaraya-watson kernel regression func-
consequences of our work, none which we feel must be                  tion estimator. (Serie Research Memoranda; No. 1988-
specifically highlighted here.                                        58). Faculty of Economics and Business Administration,
                                                                      Vrije Universiteit Amsterdam., 1988.
Acknowledgements                                                    Bishop, C. M. and Nasrabadi, N. M. Pattern recognition
Part of the compute for this project is generously supported          and machine learning, volume 4. Springer, 2006.
by the Google TPU Research Cloud program and Hyper-                 Black, S., Biderman, S., Hallahan, E., Anthony, Q., Gao,
bolic Labs. XW is supported, in part, by the Amazon Re-               L., Golding, L., He, H., Leahy, C., McDonell, K., Phang,
search Award, the Cisco Faculty Award and the Qualcomm                J., et al. Gpt-neox-20b: An open-source autoregressive
Innovation Fellowship. SK acknowledges support by NSF                 language model. arXiv preprint arXiv:2204.06745, 2022.
2046795 and 2205329, NIFA award 2020-67021-32799, the
Alfred P. Sloan Foundation, and Google Inc. TH is sup-              Bottou, L. and Vapnik, V. Local learning algorithms. Neural
ported by a Sony Faculty Innovation Award and a gift from             computation, 4(6):888–900, 1992.
Panasonic. CG acknowledges support by the Air Force Of-
fice of Scientific Research (AFOSR), FA9550-20-1-0427,              Breiman, L., Meisel, W., and Purcell, E. Variable kernel
Stanford Human-Centered Artificial Intelligence (HAI) In-             estimates of multivariate densities. Technometrics, 19(2):
stitute, and gifts from Google and IBM.                               135–144, 1977.

We would like to thank Rohan Taori, Xuechen Li, Allan               Cai, Z. Weighted nadaraya–watson regression estimation.
Zhou, Ke Chen, and Guandao Yang for many helpful discus-              Statistics & probability letters, 51(3):307–318, 2001.
sions, Menghao Guo for help with code release, Xinyang
                                                                    Chen, T., Xu, B., Zhang, C., and Guestrin, C. Training deep
Geng for help with EasyLM, Hao Liu for help with the
                                                                      nets with sublinear memory cost, 2016.
LWM codebase, David Hall for help with Levanter, Yossi
Gandelsman and Yutong Bai for help at an early stage of             Chen, Y.-C. A tutorial on kernel density estimation and
the project, Mert Yuksekgonul for help with figures in the            recent advances. Biostatistics & Epidemiology, 1(1):161–
paper, Horace He, Ben Spector, and Azalia Mirhoseini for             187, 2017.
help with systems, Sharad Vikram and Roy Frostig for an-
swering our questions about JAX and Pallas, Albert Gu and           Clark, K., Guu, K., Chang, M.-W., Pasupat, P., Hinton, G.,
Tri Dao for helping us reproduce experiments in the Mamba             and Norouzi, M. Meta-learning fast weight language
paper, and Kilian Weinberger and Percy Liang for advice on            models. arXiv preprint arXiv:2212.02475, 2022.
presentation. Yu Sun is grateful to his PhD advisors, Alexei
                                                                    Dao, T. and Gu, A. Transformers are ssms: Generalized
A. Efros and Moritz Hardt, for their many insights from
                                                                      models and efficient algorithms through structured state
years ago that eventually became part of this paper.
                                                                      space duality. arXiv preprint arXiv:2405.21060, 2024.

References                                                          De, S., Smith, S. L., Fernando, A., Botev, A., Cristian-
                                                                      Muraru, G., Gu, A., Haroun, R., Berrada, L., Chen, Y.,
Achiam, J., Adler, S., Agarwal, S., Ahmad, L., Akkaya, I.,            Srinivasan, S., et al. Griffin: Mixing gated linear recur-
  Aleman, F. L., Almeida, D., Altenschmidt, J., Altman, S.,           rences with local attention for efficient language models.
  Anadkat, S., et al. Gpt-4 technical report. arXiv preprint          arXiv preprint arXiv:2402.19427, 2024.
  arXiv:2303.08774, 2023.
                                                                    de Vries, H.  In the long (context) run, 2023.
Andrychowicz, M., Denil, M., Gomez, S., Hoffman, M. W.,               URL https://www.harmdevries.com/post/
  Pfau, D., Schaul, T., Shillingford, B., and De Freitas, N.          context-length/. Accessed: 2024-06-24.
  Learning to learn by gradient descent by gradient descent.
                                                                    Finn, C., Abbeel, P., and Levine, S. Model-agnostic meta-
 Advances in neural information processing systems, 29,
                                                                      learning for fast adaptation of deep networks. In Interna-
  2016.
                                                                      tional conference on machine learning, pp. 1126–1135.
                                                                      PMLR, 2017.
Beck, M., Pöppel, K., Spanring, M., Auer, A., Prudnikova,
  O., Kopp, M., Klambauer, G., Brandstetter, J., and                Gandelsman, Y., Sun, Y., Chen, X., and Efros, A. A. Test-
  Hochreiter, S. xlstm: Extended long short-term mem-                 time training with masked autoencoders. Advances in
  ory. arXiv preprint arXiv:2405.04517, 2024.                         Neural Information Processing Systems, 2022.

                                                               10
                           Learning to (Learn at Test Time): RNNs with Expressive Hidden States

Gao, L., Biderman, S., Black, S., Golding, L., Hoppe, T.,            Le, Q. V. Building high-level features using large scale
  Foster, C., Phang, J., He, H., Thite, A., Nabeshima, N.,             unsupervised learning. In 2013 IEEE international con-
  Presser, S., and Leahy, C. The pile: An 800gb dataset of             ference on acoustics, speech and signal processing, pp.
  diverse text for language modeling, 2020.                            8595–8598. IEEE, 2013.
Geng, X. EasyLM: A Simple And Scalable Training Frame-               Liu, H., Yan, W., Zaharia, M., and Abbeel, P. World model
  work for Large Language Models. https://github.                      on million-length video and language with blockwise
  com/young-geng/EasyLM, mar 2023. https://                            ringattention. arXiv preprint arXiv:2402.08268, 2024.
  github.com/young-geng/EasyLM.
                                                                     Maclaurin, D., Duvenaud, D., and Adams, R. Gradient-
Gu, A. and Dao, T. Mamba: Linear-time sequence
                                                                      based hyperparameter optimization through reversible
  modeling with selective state spaces. arXiv preprint
                                                                      learning. In International conference on machine learn-
  arXiv:2312.00752, 2023.
                                                                      ing, pp. 2113–2122. PMLR, 2015.
Hardt, M. and Sun, Y. Test-time training on nearest
  neighbors for large language models. arXiv preprint                Metz, L., Maheswaranathan, N., Cheung, B., and Sohl-
  arXiv:2305.18466, 2023.                                             Dickstein, J. Meta-learning update rules for unsupervised
                                                                      representation learning. arXiv preprint arXiv:1804.00222,
Hendrycks, D. and Gimpel, K. Gaussian error linear units              2018.
  (gelus). arXiv preprint arXiv:1606.08415, 2016.
                                                                     Peng, B., Goldstein, D., Anthony, Q., Albalak, A., Al-
Hinton, G. E. and Plaut, D. C. Using fast weights to deblur            caide, E., Biderman, S., Cheah, E., Ferdinan, T., Hou, H.,
  old memories. In Proceedings of the ninth annual con-                Kazienko, P., et al. Eagle and finch: Rwkv with matrix-
  ference of the Cognitive Science Society, pp. 177–186,               valued states and dynamic recurrence. arXiv preprint
  1987.                                                                arXiv:2404.05892, 2024.
Hochreiter, S. and Schmidhuber, J. Long short-term memory.
  Neural computation, 9(8):1735–1780, 1997.                          Rosenblatt, F. The perceptron: a probabilistic model for
                                                                       information storage and organization in the brain. Psy-
Irie, K., Csordás, R., and Schmidhuber, J. The dual form              chological review, 65(6):386, 1958.
   of neural networks revisited: Connecting test time pre-
   dictions to training patterns via spotlights of attention.        Schlag, I., Munkhdalai, T., and Schmidhuber, J. Learning
   In International Conference on Machine Learning, pp.                associative inference using fast weight memory. arXiv
   9639–9659. PMLR, 2022.                                              preprint arXiv:2011.07831, 2020.

Kaplan, J., McCandlish, S., Henighan, T., Brown, T. B.,              Schlag, I., Irie, K., and Schmidhuber, J. Linear transform-
  Chess, B., Child, R., Gray, S., Radford, A., Wu, J., and             ers are secretly fast weight programmers. In Interna-
  Amodei, D. Scaling laws for neural language models.                  tional Conference on Machine Learning, pp. 9355–9366.
  arXiv preprint arXiv:2001.08361, 2020.                               PMLR, 2021.
Katharopoulos, A., Vyas, A., Pappas, N., and Fleuret, F.             Schmidhuber, J. Evolutionary principles in self-referential
  Transformers are rnns: Fast autoregressive transformers              learning, or on learning how to learn: the meta-meta-
  with linear attention. In International conference on ma-            ... hook. PhD thesis, Technische Universität München,
  chine learning, pp. 5156–5165. PMLR, 2020.                           1987.
Kirsch, L. and Schmidhuber, J. Meta learning backpropaga-
  tion and improving it. Advances in Neural Information              Schmidhuber, J. Learning to control fast-weight memories:
  Processing Systems, 34:14122–14134, 2021.                            An alternative to dynamic recurrent networks. Neural
                                                                       Computation, 4(1):131–139, 1992.
Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu,
 C. H., Gonzalez, J., Zhang, H., and Stoica, I. Efficient            Shazeer, N. Glu variants improve transformer, 2020.
 memory management for large language model serving
 with pagedattention. In Proceedings of the 29th Sym-                Shleifer, S., Weston, J., and Ott, M. Normformer: Improved
 posium on Operating Systems Principles, pp. 611–626,                  transformer pretraining with extra normalization. arXiv
 2023.                                                                 preprint arXiv:2110.09456, 2021.

Lake, B. M., Ullman, T. D., Tenenbaum, J. B., and Gersh-             Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., and Liu,
  man, S. J. Building machines that learn and think like               Y. Roformer: Enhanced transformer with rotary position
  people. Behavioral and brain sciences, 40:e253, 2017.                embedding, 2023.

                                                                11
                            Learning to (Learn at Test Time): RNNs with Expressive Hidden States

Sun, Y., Wang, X., Liu, Z., Miller, J., Efros, A., and Hardt,           Zhang, B. and Sennrich, R. Root mean square layer normal-
  M. Test-time training with self-supervision for generaliza-             ization, 2019.
  tion under distribution shifts. In International Conference
  on Machine Learning, pp. 9229–9248. PMLR, 2020.                       Zhang, H., Berg, A. C., Maire, M., and Malik, J. Svm-knn:
                                                                          Discriminative nearest neighbor classification for visual
Thrun, S. and Pratt, L. Learning to learn: Introduction and               category recognition. In 2006 IEEE Computer Society
  overview. In Learning to learn, pp. 3–17. Springer, 1998.               Conference on Computer Vision and Pattern Recognition
                                                                          (CVPR’06), volume 2, pp. 2126–2136. IEEE, 2006.
Tieleman, T. and Hinton, G. Using fast weights to improve
  persistent contrastive divergence. In Proceedings of the
  26th annual international conference on machine learn-
  ing, pp. 1033–1040, 2009.
Touvron, H., Martin, L., Stone, K., Albert, P., Almahairi,
  A., Babaei, Y., Bashlykov, N., Batra, S., Bhargava, P.,
  Bhosale, S., Bikel, D., Blecher, L., Ferrer, C. C., Chen,
  M., Cucurull, G., Esiobu, D., Fernandes, J., Fu, J., Fu, W.,
  Fuller, B., Gao, C., Goswami, V., Goyal, N., Hartshorn,
  A., Hosseini, S., Hou, R., Inan, H., Kardas, M., Kerkez,
  V., Khabsa, M., Kloumann, I., Korenev, A., Koura, P. S.,
  Lachaux, M.-A., Lavril, T., Lee, J., Liskovich, D., Lu, Y.,
  Mao, Y., Martinet, X., Mihaylov, T., Mishra, P., Molybog,
  I., Nie, Y., Poulton, A., Reizenstein, J., Rungta, R., Saladi,
  K., Schelten, A., Silva, R., Smith, E. M., Subramanian, R.,
  Tan, X. E., Tang, B., Taylor, R., Williams, A., Kuan, J. X.,
  Xu, P., Yan, Z., Zarov, I., Zhang, Y., Fan, A., Kambadur,
  M., Narang, S., Rodriguez, A., Stojnic, R., Edunov, S.,
  and Scialom, T. Llama 2: Open foundation and fine-tuned
  chat models, 2023.
Vincent, P., Larochelle, H., Bengio, Y., and Manzagol, P.-A.
  Extracting and composing robust features with denoising
  autoencoders. In ICML, pp. 1096–1103, 2008.
Wang, R., Sun, Y., Gandelsman, Y., Chen, X., Efros, A. A.,
 and Wang, X. Test-time training on video streams. arXiv
 preprint arXiv:2307.05014, 2023.
Wolf, T., Debut, L., Sanh, V., Chaumond, J., Delangue, C.,
 Moi, A., Cistac, P., Rault, T., Louf, R., Funtowicz, M.,
 et al. Huggingface’s transformers: State-of-the-art natural
 language processing. arXiv preprint arXiv:1910.03771,
 2019.
Xiong, W., Liu, J., Molybog, I., Zhang, H., Bhargava, P.,
  Hou, R., Martin, L., Rungta, R., Sankararaman, K. A.,
  Oguz, B., Khabsa, M., Fang, H., Mehdad, Y., Narang, S.,
  Malik, K., Fan, A., Bhosale, S., Edunov, S., Lewis, M.,
  Wang, S., and Ma, H. Effective long-context scaling of
  foundation models, 2023.
Yang, S., Wang, B., Shen, Y., Panda, R., and Kim, Y. Gated
  linear attention transformers with hardware-efficient train-
  ing. arXiv preprint arXiv:2312.06635, 2023.
Yang, S., Wang, B., Zhang, Y., Shen, Y., and Kim, Y. Par-
  allelizing linear transformers with the delta rule over se-
  quence length. arXiv preprint arXiv:2406.06484, 2024.

                                                                   12
                                Learning to (Learn at Test Time): RNNs with Expressive Hidden States

Appendix
A. Dual Form
Here we derive the dual form for general MLPs of arbitrary depth, with nonlinear activations.
Without loss of generality, consider η = 1 for convenience, and consider only the first mini-batch, where t = 1, . . . , b.
Denote:
                                        x̂t = θK xt , yt = θV xt , x̄t = θQ xt .
Also denote X̂ = [x̂1 , . . . , x̂b ], and Y and X̄ analogously. In general, uppercase letters denote matrices whose columns are
vectors denoted by the corresponding lowercase letter.
For a network with K layers, denote the initial parameters in layer k by W0k . Our convention is to use superscripts for the
layer and subscripts for time.

A.1. Forward pass
During the initial forward pass of TTT, we denote the input to layer k by X̂ k = [x̂k1 , . . . , x̂kb ], with X̂ 1 = X̂. Now we write
the forward pass of TTT using these notations.
For k = 1, . . . , K:

   • Z k = W0k X̂ k
                          
   • X̂ k+1 = σk Z k

where σk for k = 1, . . . , K can be any element-wise operation (R 7→ R) with derivative σ ′ .
Given X̂ K+1 , we compute the loss:
                                                                                                  b
                                         1                        1                         2   X
                                      l = ℓ W01 , . . . , W0K ; X =   X̂ K+1 − Y             F
                                                                                               =     lt ,
                                         2                          2                            t=1

where lt = 12 ∥x̂K       2
                 t − yt ∥ is the same as defined in Equation 3, except scaled by 1/2 for convenience.

All the operations above (except σ) are matmuls and sums, therefore are hardware efficient. Both the primal form and the
dual form share these initial operations.

A.2. Primal form
                                                                                                            Pt
The primal form first computes Gkt = ∇W0k lt for t = 1, . . . , b, then updates Wtk = W0k −                       k
                                                                                                             s=1 Gs .   Finally, given
X̄ 1 = [x̄11 , . . . , x̄1b ] = X̄, the primal form repeats the forward pass with the updated W s.
For k = 1, . . . , K:

   • z̄tk = Wtk x̄kt , for t = 1, . . . , T
   • x̄k+1
       t   = σk (z̄tk ), for t = 1, . . . , T

where X̄ K+1 = [x̄k+1
                  1   , . . . , x̄k+1
                                  b   ] contains the output tokens.
Note that a standard backward pass only computes the sum of the gradients:
                                                             b
                                                             X                 b
                                                                               X
                                                  ∇W0k l =         ∇W0k lt =         Gkt ,
                                                             t=1               t=1

so the computation of the individual terms in the sum Gkt for t = 1, . . . , b cannot be batched together into matmuls.
Similarly, the forward pass in primal form uses a different Wt for each x̄t , therefore also cannot be batched in the same way
as a standard forward pass. These non-standard passes have poor hardware efficiency.

                                                                   13
                                 Learning to (Learn at Test Time): RNNs with Expressive Hidden States

A.3. Dual form
As discussed in Subsection 2.5, the goal of the dual form is to compute X̄ K+1 and Wb1 , . . . , WbK with only matmuls and
light-weight operations such as sums, σ, and σ ′ . To achieve this goal, we avoid explicitly computing the intermediate
variables: Gkt and Wtk for t = 1, . . . , b.
The dual form first computes ∇X̂ K+1 l = X̂ K+1 − Y , then takes a standard backward pass.
For k = K, . . . , 1:

   • ∇Z k l = σk′ Z k ⊙ ∇X̂ k+1 l
                     

                        T
   • ∇X̂ k l = W0k           ∇Z k l
                               T
   • ∇W0k l = ∇Z k l X̂ k

where σ ′ is applied element-wise, and ⊙ is element-wise multiplication.
Now we can already compute Wbk = W0k − ∇W0k l. To compute the output tokens, we do another forward pass.
For k = 1, . . . , K:
                                                   T          
   • Z̄ k = W0k X̄ k − ∇Z k l · mask          X̂ k        X̄ k
                         
   • X̄ k+1 = σ Z̄ k

By the end of the forward pass, we have computed X̄ K+1 .
While this forward pass is non-standard, it only contains matmuls, sums, σ, and mask, therefore is efficient like the
standard forward pass.

A.4. Derivation
To derive the dual form, we show that:
                                                                                             T            
                                                k
                                           Z̄       = W0k X̄ k − ∇Z k l · mask        X̂   k
                                                                                                    X̄   k



is the same as what would be computed in the primal form. Specifically, we show that each column z̄tk of Z̄ k in the second
forward pass of the dual equals to Wtk x̄kt in the forward pass of the primal. We invoke a simple fact.
                                                                                                                 Pt
Fact 1. Define matrices A = [a1 , . . . , ab ], Q = [q1 , . . . , qb ], and V = [v1 , . . . , vb ].3 Define v̂t = s=1 aTs qt vs , and
V̂ = [v̂1 , . . . , v̂b ], then V̂ = V · mask(AT Q).

Now plug A = X̂ k , Q = X̄ k , V = ∇Z k l, and V̂ = W k X̄ k − Z̄ k into the fact above, we have shown the desired equality.
Note that the σk and σk′ used above can be extended to arbitrary functions that are not necessarily element-wise operations,
including normalization layers. This extension can be achieved through, for example, vjp (vector-Jacobian product)
in standard libraries for automatic differentiation such as JAX and PyTorch. However, the dual form cannot accelerate
operations inside σ or its vjp.




   3
       Our matrix A would usually be denoted by K in another context. We use A to avoid confusion with the layer number K.

                                                                     14
                            Learning to (Learn at Test Time): RNNs with Expressive Hidden States

B. Nadaraya-Watson estimator
Derivation for the Nadaraya-Watson estimator. Throughout this section, we use x to denote the input token x as a random
variable. Our desired output is the corresponding output token, another random variable z. This is formulated as estimating
the conditional expectation of z:
                                                    Z                 Z
                                                                          p(x, z)
                                      E[z|x = x] = p(z|x) z dz =                  z dz.
                                                                           p(x)

Since the true probability distributions p(x) and p(x, z) are unknown, we replace them with their kernel density estimations.
Specifically, the kernel density estimation for p(x) is:
                                                                    n
                                                               1X
                                                     p̂(x) =         κ(x, xi ),
                                                               n i=1

where each xi is a piece of training data in general. (Recall that for our paper, xi is specifically training data for the inner
loop, i.e. a token, which matches our notation in the main text.)
For estimating p(x, y), we use the product kernel:
                                                               n
                                                           1X
                                              p̂(x, z) =         κ(x, xi ) κ′ (z, zi ).
                                                           n i=1

At first sight, it seems absurd to factor the joint probability into two seemingly independent kernels. But in this case, κ′ can
actually be any κ′i dependent on xi , since it will be integrated out. So the two kernels do not need to be independent.
Plugging in those estimations, we obtain the Nadaraya-Watson estimator:
                                             Z
                                                 p̂(x, z)
                               Ê[z|x = x] =               z dz
                                                   p̂(x)
                                                     Z
                                                1
                                           =            p̂(x, z) z dz
                                              p̂(x)
                                                                Z X  n
                                                      1
                                           = Pn                         κ(x, xi ) κ′ (z, zi ) z dz
                                                 i=1 κ(x, xi )      i=1
                                                                  n            Z
                                                      1         X
                                           = Pn                      κ(x, xi )    κ′ (z, zi ) z dz
                                                 i=1 κ(x, xi ) i=1
                                                                   n
                                                        1         X
                                              = Pn                    κ(x, xi ) zi .
                                                    i=1 κ(x, xi ) i=1


Asymmetric kernels. In modern days, people think of kernels as positive semi-definite, which might not be guaranteed for
κ unless θK = θQ . However, people working on kernels decades ago, around the time when the Nadaraya-Watson estimator
was popular, have been very lenient with the choice of kernels, and asymmetric kernels such as our κ in Equation 9 have
enjoyed a long tradition: When a kernel estimator uses θK ̸= θQ , it is known as a balloon estimator (Chen, 2017). Papers
such as Breiman et al. (Breiman et al., 1977) have even used θQ as a function of x′ , known as sample-adaptive smoothing.




                                                                   15
                              Learning to (Learn at Test Time): RNNs with Expressive Hidden States

       Residual block                           Transformer backbone                                    Mamba backbone



           MLP block




           LayerNorm                                         LayerNorm                                        LayerNorm



                                                             TTT layer                                        TTT layer

           Sequence
         modeling block                                                                                   Conv         Conv




           LayerNorm                                                                                               /              Gate




Figure 9. Left: A residual block, the basic building block for Transformers. The sequence modeling block is instantiated into two variants:
the Transformer backbone and Mamba backbone. Middle: TTT layer in the Transformer backbone. The LN before O comes from
NormFormer (Shleifer et al., 2021). Right: TTT layer in the backbone inspired by Mamba (Gu & Dao, 2023) and Griffin (De et al., 2024).
Following these two architectures, σ here is GELU (Hendrycks & Gimpel, 2016). To accommodate the extra parameters of the gate
without changing the embedding dimension, we simply combine θK and θQ into a single projection.



C. Experiment details
Architectures. Our Transformer strictly follows the construction in the Mamba paper, where Transformer is called
Transformer++. Specifically, the Transformer architecture is based on Llama (Touvron et al., 2023), with rotary positional
encodings (RoPE) (Su et al., 2023), SwiGLU MLP blocks (Shazeer, 2020), and RMSNorm (Zhang & Sennrich, 2019)
instead of LayerNorm. Our Mamba baseline uses the public code provided by the authors. We have verified that our
baselines can reproduce the numbers reported in (Gu & Dao, 2023).
Training configurations. Our training configurations are in Table 2, which simply reproduces Table 12 in the Mamba
paper. All models are trained with a batch size of 0.5M tokens regardless of context length. All of our optimization
hyper-parameters follow the “improved recipe” in Appendix E.2 of the Mamba paper, reproduced below:

   • AdamW optimizer: β = (0.9, 0.95)
   • Cosine schedule: decay to end learning rate 1e − 5
   • Linear learning rate warmup over 10% of the training steps
   • Weight decay: 0.1
   • Gradient clipping: 1.0
   • No Dropout
   • Mixed Precision

For experiments on the Pile, this is the only difference with the recipe in the Mamba paper, which uses two other tokenizers.
For experiments on Books, we find that the original angle of the RoPE encoding (Su et al., 2023) θ = 10, 000 is sub-optimal

                                                                   16
                              Learning to (Learn at Test Time): RNNs with Expressive Hidden States


                       Params.     Blocks      Embed. dim.      Heads      Train steps    Peak LR      Tokens

                       125M           12            768           12          4800           3e-3        2.5B
                       350M           24           1024           16         13500          1.5e-3        7B
                       760M           24           1536           16         29000         1.25e-3       15B
                       1.3B           24           2048           32         50000           1e-3        26B

Table 2. Training configurations for all experiments. This table reproduces Table 12 in the Mamba paper. The only difference is that the
learning rate they use for Mamba and Transformer is 5× the values in their Table 12, and we report the actual values (5×). Note that
this table only applies to TTT-Linear, TTT-MLP, and Transformers, as Mamba does not follow the multi-head residual block structure
inherited from Transformers.


for our Transformer baseline in long context. Starting at context length 4k, we try θ = 500, 000 following the Llama Long
paper (Xiong et al., 2023), and use the better perplexity for Transformer (both pretrain and finetune).
Transformer finetuning. Finetuning starts a new cosine schedule with the same optimization hyper-parameter as training
from scratch, except the peak learning rate. We try three peak learning rates for finetuning: 1e-5, 1e-4, and 1e-3, and select
for the best perplexity. We observe that 1e-4 works the best for the 125M models, while 1e-5 works the best for 350M and
larger. This observation is reasonable considering that the end learning rate for the Chinchilla recipe is 1e-5.
Learning rate for TTT. As mentioned in Subsection 2.7, the inner-loop base learning rate ηbase is set to 1 for TTT-Linear
and 0.1 for TTT-MLP. Our heuristic for setting ηbase is similar to how people set the outer-loop learning rate for regular
training: We tried ηbase ∈ {0.01, 0.1, 1, 10} and used the largest value that does not cause instabilities. For TTT-MLP, we
use linear warmup for ηbase over 10% of the training steps, similar to regular training. The number of training steps in
the inner loop is T /b (assume divisible). For TTT-Linear, we tried linear warmup in the inner loop but did not observe a
difference.
Experiments in Figure 1 (right). To ensure fairness to Mamba, all methods in these experiments have matched training
FLOPs and are trained with the same recipe (last row of Table 2) as Mamba 1.4B. For TTT-Linear and TTT-MLP, matched
training FLOPs also imply matched inference FLOPs. Transformer (TF finetune) has 2.8× the inference FLOPs, giving it an
advantage as our baseline. To match training FLOPs with Mamba, Transformer has 19 blocks instead of 24. For TTT-Linear
and TTT-MLP, their training FLOPs are already close to those of Mamba, so we only need to change the hidden dimension
of the MLP blocks from 5504 to 5808 for TTT-Linear and 5248 for TTT-MLP.
Gradient checkpointing through time. By default, libraries such as JAX and PyTorch save the intermediate activations
during a forward pass so they can be reused during the backward pass. However, for a TTT layer with W as hidden state,
this default saves W1 , . . . , WT , which uses too much memory. With TTT mini-batch and the dual form, we still need to
save (assume divisible) κ = T /b W s at the end of the mini-batches. A standard technique to save memory in this scenario is
gradient checkpointing (Chen et al., 2016), which is usually applied through layers, but we apply it through time.




                                                                  17
                                  Learning to (Learn at Test Time): RNNs with Expressive Hidden States




           1.8
                                                             1.0                                                1.0
           1.6
                                                             0.9                                                0.9
           1.4                       (W0; xt)                                           (W0; xt)                                        (W0; xt)
TTT loss




                                                  TTT loss




                                                                                                     TTT loss
                                     (Wt 1; xt)              0.8                        (Wt 1; xt)                                      (Wt 1; xt)
                                     (Wt; xt)                                           (Wt; xt)                0.8                     (Wt; xt)
           1.2
                                                             0.7                                                0.7
           1.0
                                                             0.6                                                0.6
                 0   500 1000 1500 2000                            0   500 1000 1500 2000                             0   500 1000 1500 2000
                        Token index t                                     Token index t                                      Token index t
                                                             1.1                                                0.9
           1.8
                                                             1.0                                                0.8
           1.6                                                                 (W0; xt)                                        (W0; xt)
                                                             0.9
TTT loss




                                                  TTT loss




                                                                                                     TTT loss
           1.4                                                                 (Wt 1; xt)                       0.7            (Wt 1; xt)
                                                             0.8               (Wt; xt)                                        (Wt; xt)
           1.2                       (W0; xt)                                                                   0.6
                                     (Wt 1; xt)              0.7
           1.0                       (Wt; xt)                0.6                                                0.5
                 0   500 1000 1500 2000                            0   500 1000 1500 2000                             0   500 1000 1500 2000
                        Token index t                                     Token index t                                      Token index t
           1.1
           1.0                                               1.6
                                                                                                                1.6
           0.9       (W0; xt)                                1.4                                                               (W0; xt)
TTT loss




                                                  TTT loss




                                                                                                     TTT loss
                     (Wt 1; xt)                                                                                 1.4            (Wt 1; xt)
           0.8       (Wt; xt)                                1.2                        (W0; xt)                               (Wt; xt)
                                                                                        (Wt 1; xt)              1.2
           0.7                                               1.0                        (Wt; xt)
                 0   500 1000 1500 2000                            0   500 1000 1500 2000                             0   500 1000 1500 2000
                        Token index t                                     Token index t                                      Token index t

                                                                                                                2.0
           2.0                                               1.6
                                                                                        (W0; xt)                1.8                     (W0; xt)
           1.8                                               1.4
TTT loss




                                                  TTT loss




                                                                                                     TTT loss




                                                                                        (Wt 1; xt)              1.6                     (Wt 1; xt)
                                     (W0; xt)                1.2                        (Wt; xt)                                        (Wt; xt)
           1.6
                                     (Wt 1; xt)                                                                 1.4
           1.4                       (Wt; xt)                1.0
                                                                                                                1.2
                 0   500 1000 1500 2000                            0   500 1000 1500 2000                             0   500 1000 1500 2000
                        Token index t                                     Token index t                                      Token index t


Figure 10. The self-supervised TTT loss ℓ averaged over all test sequences of the form x1 , . . . , xT where T = 2048, for all 12 TTT
layers in a network with 125M parameters train on the Pile. The same network is also used for b = 1 (online GD) in the left panel of
Figure 4. For layers in the middle, we observe that ∥xt ∥ rises steadily, causing all three losses to rise with it. Even for these layers, the
gap between ℓ(W0 ; xt ) and ℓ(Wt ; xt ) still increases with t . For visual clarity, loss values have been averaged over a sliding window of
10 timesteps.




                                                                          18
                                   Learning to (Learn at Test Time): RNNs with Expressive Hidden States



                                           1k                                                                          2k
                          18
                                                             TF pretrain                             17                                    TF pretrain
                          17                                 Mamba                                                                         Mamba
                                                                                                     16
                          16                                 TTT-Linear                                                                    TTT-Linear
                                                             TTT-MLP                                 15                                    TTT-MLP
                          15
Perplexity (log scale)




                                                                           Perplexity (log scale)
                                                                                                     14
                          14
                                                                                                     13
                          13
                                                                                                     12
                          12
                                                                                                     11
                          11
                                                                                                    101
                         101
                                                                                                      9
                                     1019                    1020                                               1019                      1020
                                    FLOPs (log scale)                                                           FLOPs (log scale)
                                           4k                                                                          8k
                          17                                 TF finetune                                                                   TF finetune
                          16                                 TF pretrain                             16                                    TF pretrain
                          15                                 Mamba                                                                         Mamba
                                                             TTT-Linear                                                                    TTT-Linear
                          14                                 TTT-MLP                                 14                                    TTT-MLP
Perplexity (log scale)




                                                                           Perplexity (log scale)



                          13
                          12                                                                         12
                          11
                         101                                                                        101

                           9
                                   1019                  1020                                                  1019                     1020
                                   FLOPs (log scale)                                                            FLOPs (log scale)
                                          16k                                                                         32k
                          18                                 TF finetune                                                                   TF finetune
                                                                                                     18
                                                             TF pretrain                                                                   TF pretrain
                          16                                 Mamba                                                                         Mamba
                                                             TTT-Linear                              16                                    TTT-Linear
                                                             TTT-MLP                                                                       TTT-MLP
Perplexity (log scale)




                                                                           Perplexity (log scale)




                          14                                                                         14

                          12                                                                         12

                         101                                                                        101



                           1018   1019                1020                                            1018   1019                1020
                                    FLOPs (log scale)                                                           FLOPs (log scale)


Figure 11. Complete results on Books, presented by context lengths. Figure 7 in Subsection 3.2 presents the subset of results for context
lengths 2k and 32k.



                                                                           19
                                                   Learning to (Learn at Test Time): RNNs with Expressive Hidden States




                                                      125M                                                                                         350M
                         18.5        TF finetune                                                                 12.8
                                     TF pretrain
                         18.0        Mamba                                                                       12.6
perplexity (log scale)




                                                                                        perplexity (log scale)
                                     TTT-Linear                                                                  12.4
                         17.5        TTT-MLP
                                                                                                                 12.2
                         17.0
                                                                                                                 12.0
                                                                                                                                   TF finetune
                         16.5                                                                                    11.8              TF pretrain
                                                                                                                                   Mamba
                         16.0                                                                                    11.6              TTT-Linear
                                                                                                                 11.4              TTT-MLP
                                2k         4k          8k           16k      32k                                              2k         4k          8k           16k   32k
                                            context length (log scale)                                                                    context length (log scale)
                                                      760M                                                                                          1.3B
                                                                                                                        9.4
                         10.4
                                                                                                                        9.2
perplexity (log scale)




                                                                                               perplexity (log scale)




                         10.2
                                                                                                                        9.0
                         101
                                                                                                                        8.8
                          9.8        TF finetune                                                                                   TF finetune
                                     TF pretrain                                                                        8.6        TF pretrain
                          9.6        Mamba                                                                                         Mamba
                                     TTT-Linear                                                                                    TTT-Linear
                                     TTT-MLP                                                                            8.4        TTT-MLP
                          9.4
                                2k         4k          8k           16k      32k                                              2k         4k          8k           16k   32k
                                            context length (log scale)                                                                    context length (log scale)


Figure 12. An alternative view of our complete results on Books, presented by model sizes, with context length as the x-axis. For all
methods trained from scratch, perplexity becomes worse once the context length becomes too large. This trend is not observed with TF
finetune, except for one case at the 125M scale. The best context length increases for larger models (trained from scratch).




                                                                                   20
