\chapter{Sequential Memory with Temporal Predictive Coding}\label{chap:seqmem}

\section{Introduction}

The ability to memorize and recall sequences of events with temporal dependencies is crucial for biological memory systems that also underpins many other neural processes \citep{tulving1972episodic,eichenbaum2013memory,eichenbaum2014time}. For example, forming correct memories of words requires humans to memorize not only individual letters but also the sequential order following which the letters appear (e.g., ``cat'' and ``act''). However, despite extensive research into models of \emph{static}, temporally unrelated memories from both neuroscience and machine learning \citep{hopfield1982neural,krotov2016dense,ramsauer2020hopfield,millidge2022universal,salvatori2021associative,iatropoulos2022kernel,tang2023recurrent}, computational modeling of \emph{sequential} memory is not as developed. Existing models for sequential memory are either analytically intractable or have not yet been systematically evaluated in challenging sequential memory tasks \citep{wallenstein1998hippocampus, rolls2010computational,hawkins2009sequence, sompolinsky1986temporal,chaudhry2023modern}, which hinders a comprehensive understanding of the computational mechanism underlying sequential memory, arguably a more general form of memory in the natural world than static memories.


% Recent works have shown that, similar to the modern variants of HNs \citep{krotov2016dense,ramsauer2020hopfield}, AHNs can also be ``modernized'' to have large sequence capacities \citep{chaudhry2023modern}. 
% However, these models have not yet been explored in sequential memory tasks involving complex and structured inputs, such as natural movies.

In this chapter, we propose a novel approach to modeling sequential memory based on predictive coding \citep{rao1999predictive,friston2003learning,bogacz2017tutorial}, a biologically plausible neural network model able to reproduce many phenomena observed in the brain \citep{walsh2020evaluating}, which has also shown to have a close relationship to backpropagation in artificial neural networks \citep{whittington2017approximation,song2020can}. Using predictive coding to model sequential memory is motivated by two key factors: Firstly, neuroscience experiments and theories have suggested that (temporal) predictive processing and memory are two highly related computations in the hippocampus, the brain region crucial for memory \citep{barron2020prediction,lisman2009prediction}. Secondly, the modeling of static memories (e.g., a single image) using predictive coding has recently demonstrated significant success \citep{salvatori2021associative,yoo2022bayespcn,tang2023recurrent,salvatori2022learning}, raising the question of whether predictive coding can also be employed to model sequential memory. To take into account the temporal dimension in sequential memory, in this chapter we adopt the temporal predictive coding (tPC) model introduced earlier in this thesis (Chapter \ref{chap:time}), although we also introduce a simpler, single-layer version of tPC in this chapter. The contributions of this chapter can be summarized as follows:
% \vspace{-1mm}
\begin{itemize}[leftmargin=*]
    \item We show that tPC is capable of sequential memory tasks with a biologically plausible neural network implementation;
    % , and can be flexibly extended to have a multi-layer structure;
    \item We present an analytical result showing that the single-layer tPC can be viewed as the classical Asymmetric Hopfield Network (AHN) performing an implicit {statistical whitening} step during memory recall,
    % which provides not only a theoretical understanding of why tPC performs sequential memory but also
    providing a possible mechanism of statistical whitening in the brain \citep{duong2023statistical,pehlevan2019neuroscience,golkar2022constrained};
    \item Experimentally, we show that the whitening step in single-layer tPC models results in more stable performance than the AHN and its modern variants \citep{chaudhry2023modern} in sequential memory, due to the highly variable and correlated structure of natural sequential inputs;
    \item We show that tPC can successfully reproduce several behavioral observations in humans, including the impact of sequence length in word memories and the primacy/recency effect;
    \item Beyond memory, we show that our tPC model can also develop context-dependent representations \citep{eichenbaum2013memory,wallenstein1998hippocampus} and generalize learned dynamics to unseen sequences, suggesting a potential connection to cognitive maps in the brain \citep{tolman1948cognitive,behrens2018cognitive}.
\end{itemize}

\section{Background: Asymmetric Hopfield Networks}
% \subsection{Predictive Coding Models for Static Memory}

% The original PC model for memory follows a hierarchical and generative structure, where higher layers generate top-down predictions of lower layers' activities and the network's learning and inference are driven by the minimization of all the prediction errors \citep{salvatori2021associative}. Since the memorized patterns minimize the prediction errors in PC, they can be considered attractors of the energy function defined as the (summed) prediction errors, which is similar to the energy perspective of Hopfield Networks (HNs) \citep{hopfield1982neural}. \citet{tang2023recurrent} have also shown that PC models for memory can be formulated as recurrent networks to account for the recurrently connected hippocampal network (see also Chapter \ref{chap:am}). Moreover, continual memorization and recall of a stream of patterns can be achieved by combining the hierarchical PC model with conjugate Bayesian updates \citep{yoo2022bayespcn}. Despite these abundant investigations into the memory capability of PC models, they all focused on static memories. Although the BayesPCN model \citep{yoo2022bayespcn} is capable of recalling patterns memorized in an online manner, the memories stored in this model are still static, order-invariant patterns, rather than sequences of patterns with underlying temporal dependencies.  

% \subsection{Predictive Coding with Time}

% PC was extended to include temporal predictions by earlier works (see \citet{rao2023predictive} for a review) noticing its relationship to Kalman filters \citep{kalman1960new}. However, the Kalman filtering approach to temporal predictions sacrifices the plausible neural implementation of PC models due to non-local computations, and a recent work proposed an alternative way of formulating PC with temporal predictions that inherits the plausible implementation of static PC, while approximating Kalman filters \citep{millidge2023temporal}. However, none of these models were examined in memory tasks. 

% As has been discussed in Chapter \ref{chap:time}, models based on temporal predictions were proposed in both neuroscience and machine learning \citep{chen2022hippocampus,jiang2022dynamic,oord2018representation,ororbia2020continual}. However, these models are either trained by the implausible backpropagation or rely on complex architectures to achieve temporal predictions. In this chapter, we will adopt the tPC model proposed in Chapter \ref{chap:time} and \citet{millidge2024predictive}, which inherits the simple and biologically plausible neural implementation of classical PC models that requires only local computations and Hebbian plasticity.


Although there exist other models of sequential memory \citep{wallenstein1998hippocampus, rolls2010computational,hawkins2009sequence}, these models are mostly on the conceptual level, used to provide theoretical accounts for physiological observations from the brain, and are thus hard to analyze mathematically. Therefore, here we focus our discussion on the AHN \citep{sompolinsky1986temporal} and its modern variants \citep{chaudhry2023modern}, which extended the HN \citep{hopfield1982neural} to account for sequential memory, and have a more explicit mathematical formulation. Denoting a sequence of $K+1$ patterns $\mathbf{x}_{k}$ ($k=1,...,K+1$), $\mathbf{x}^k \in \{-1, 1\}^N$, the $N\times N$ weight matrix of an AHN is set as follows:
\begin{eqnarray}
    \bfW^{AHN} = \sum_{k=1}^K \mathbf{x}_{k+1}\mathbf{x}_{k}^\top
\end{eqnarray}

Notice that it differs from the static HN only by encoding the asymmetric autocovariance rather than the symmetric covariance $\sum_{k=1}^K \mathbf{x}_{k}\mathbf{x}_{k}^\top$, thus the name. The single-shot retrieval, which we define as $R$, is then triggered by a query, $\mathbf{q}\in \{-1, 1\}^N$:
\begin{eqnarray}\label{eq:AHN-retrieval}
    R^{AHN}(\mathbf{q}) = \sgn(\bfW^{AHN}\mathbf{q}) = \sgn\left(\sum_{k=1}^K \mathbf{x}_{k+1}\mathbf{x}_{k}^\top \mathbf{q} \right)
\end{eqnarray}

The retrieval process in Eq \ref{eq:AHN-retrieval} can be viewed as follows: the query $\mathbf{q}$ is first compared with each $\mathbf{x}_{k}$ using a dot product function $\mathbf{x}_{k}^\top \mathbf{q}$ that outputs a similarity score, then the retrieval is a weighted sum of all $\mathbf{x}_{k+1}$ ($k=1,...,K$) using these scores as weights. Thus, if $\mathbf{q}$ is identical to a certain $\mathbf{x}_k$, the next pattern $\mathbf{x}_{k+1}$ will be given the largest weight in the output retrieval. Following the Universal Hopfield Network (UHN) framework \citep{millidge2022universal}, we can generalize this process to define a retrieval function of a general sequential memory model with real-valued patterns $\mathbf{x}_k \in\mathbb{R}^N$:
\begin{eqnarray}\label{eq:UHN-retrieval}
    R^{UHN}(\mathbf{q}) =  \sum_{k=1}^K \mathbf{x}_{k+1}\sep\left(\simi(\mathbf{x}_{k}, \mathbf{q})\right)
\end{eqnarray}
where $\simi$ is a similarity function such as dot product or cosine similarity, and $\sep$ is a separation function that separates the similarity scores i.e., emphasize large scores and de-emphasize smaller ones \citep{millidge2022universal}. When $\simi$ is dot product and $\sep$ is an identity function, we get the retrieval function of the original AHN (for binary patterns an ad-hoc $\sgn$ function can be applied to the retrievals). 
% In static memory tasks, UHN have provided a unifying view of the Dense Associative Memory \citep{krotov2016dense}, which uses a polynomial $\sep$ function with degree $d$ and dot product $\simi$ function, and the Modern Continuous Hopfield Network \citep{ramsauer2020hopfield}, which uses a $\softmax$ $\sep$ function and dot product $\simi$ function. Similarly, 
\citet{chaudhry2023modern} have shown that it is possible to extend AHN to a model with polynomial $\sep$ function with a degree $d$, and a model with $\softmax$ $\sep$ function, which we call ``Modern Continuous AHN'' (MCAHN):
\begin{eqnarray}\label{eq:recall-MAHN}
    R^{AHN}(\mathbf{q}, d) =  \sum_{k=1}^K \mathbf{x}_{k+1}\left(\mathbf{x}_{k}^\top \mathbf{q} \right)^d
\end{eqnarray}
\begin{eqnarray}\label{eq:recall-MCAHN}
     R^{MCAHN}(\mathbf{q}, \beta) =  \sum_{k=1}^K \mathbf{x}_{k+1}\softmax\left(\beta\mathbf{x}_{k}^\top \mathbf{q}\right)
\end{eqnarray}
where $\beta$ is the temperature parameter that controls the separation strength of the MCAHN. Note that these two models can be respectively viewed as sequential versions of the Modern Hopfield Network \citep{krotov2016dense} and the Modern Continuous Hopfield Network \citep{ramsauer2020hopfield}, which is closely related to the self-attention mechanism in Transformers \citep{vaswani2017attention}.
% When $d=1$ in Eq \ref{eq:recall-MAHN}, we get the retrieval function of the original AHN (for binary patterns an ad-hoc $\sgn$ function can be applied to the retrievals). 
% From a machine learning perspective, the retrieval of UHNs is reminiscent of the self-attention mechanism in Transformers \citep{vaswani2017attention,ramsauer2020hopfield}, and may also be considered as kernels \citep{iatropoulos2022kernel}. 
However, the family of AHNs has not yet been investigated in sequential memory tasks with structured and complex inputs such as natural movies.



\section{Models}

In this section, we introduce the tPC models by describing their computations during {\bf memorization} and {\bf recall} respectively, as well as the {\bf neural implementations} of these computations. We describe the single-layer tPC first, and then move to the 2-layer tPC.

\subsection{Single-layer tPC}

\paragraph{Memorization}
The most straightforward intuition behind ``good'' sequential memory models is that they should learn the transition between every pair of consecutive patterns in the sequence, so that accurate recall of the full sequence can be achieved recursively by recalling the next pattern based on the current one. Given a sequence of real-valued patterns $\mathbf{x}_k$, $k=1,...,K+1$, this intuition can be formalized as the model minimizing the following loss at each time-step:
\begin{eqnarray}\label{eq:single-layer-energy}
    \mathcal{F}_k (\bfW) = \Vert \mathbf{x}_k - \bfW f(\mathbf{x}_{k-1}) \Vert_2^2
\end{eqnarray}
which is simply the squared temporal prediction error. $\bfW$ is the weight parameter of the model, and $f(\cdot)$ is a nonlinear function. Similar to static PC models \citep{salvatori2021associative,tang2023recurrent}, we assume that the model has two populations of neurons: value neurons that are loaded with the inputs $\mathbf{x}_k$ at step $k$, and error neurons representing the temporal prediction error $\bm{\epsilon}:=\mathbf{x}_k - \bfW f(\mathbf{x}_{k-1})$. To memorize the sequence, the weight parameter $\bfW$ is updated at each step following gradient descent:
\begin{eqnarray}\label{eq:weight-update-single-layer}
    \Delta \bfW \propto -\frac{\partial \mathcal{F}_k(\bfW)}{\partial \bfW} = \bm{\epsilon}f(\mathbf{x}_{k-1})^\top
\end{eqnarray}
and the model can be presented with the sequence for multiple epochs until $\bfW$ converges. Note that the model only has one weight parameter for the whole sequence, rather than $K$ weight parameters for a sequence of length $K+1$.
% , which is equivalent to $P$ hetero-associative memories instead of one sequential memory.

\paragraph{Recall}
During recall, the weight matrix $\bfW$ is fixed to the learned values, and the value neurons no longer receive the correct patterns $\mathbf{x}_k$. Instead, while trying to recall the pattern $\mathbf{x}_k$ based on the  query $\mathbf{q}$, the value neurons are updated to minimize the squared temporal prediction error based on the query $\mathbf{q}$ and the learned $\bfW$:
\begin{eqnarray}\label{eq:single-layer-energy-recall}
    \mathcal{F}_k (\hat{\mathbf{x}}_k) = \Vert \hat{\mathbf{x}}_k - \bfW f(\mathbf{q}) \Vert_2^2
\end{eqnarray}
where we denote the value neurons' activities during recall as $\hat{\mathbf{x}}_k$ to differentiate it from the memorized patterns $\mathbf{x}_k$. The value neurons then perform the following inferential dynamics to minimize the loss $\mathcal{F}_k (\hat{\mathbf{x}}_k)$:
\begin{eqnarray}\label{eq:single-layer-recall}
    \dot{\hat{\mathbf{x}}}_k \propto -\frac{\partial \mathcal{F}_k(\hat{\mathbf{x}}_k)}{\partial \hat{\mathbf{x}}_k} = -\bm{\epsilon}
\end{eqnarray}
and the converged $\hat{\mathbf{x}}_k$ is the final retrieval. Note that the error neurons' activities during recall are defined as $\bm{\epsilon}:=\hat{\mathbf{x}}_k - \bfW f(\mathbf{q})$, which is also different from their activities during memorization. 

In the case of sequential memory, there are two types of recall. We define the first type as ``online'' recall, where the query $\mathbf{q}$ at each step $k$ is the ground-truth pattern at the previous step $\mathbf{x}_{k-1}$. It is called online as these ground-truth queries can be viewed as real-time online feedback during the sequence recall. In this case, the original $\mathbf{x}_k$ will define a memory attractor as it defines an optimum of the loss, or energy in Eqs~\ref{eq:single-layer-energy} and \ref{eq:single-layer-energy-recall}. The second type is referred to as ``offline'' recall, where $\mathbf{q}$ is the recall from the previous step i.e., $\hat{\mathbf{x}}_{k-1}$, except at the first step, where a ground-truth $\mathbf{x}_1$ is supplied to elicit recall of the whole sequence. This is called offline as there is no real-time feedback. In this case, errors from earlier steps may accumulate through time and $\mathbf{x}_k$ is no longer an ascertained attractor unless $\hat{\mathbf{x}}_{k-1}={\mathbf{x}}_{k-1}$, which makes it more challenging and analogous to the replay of memories during sleep \citep{olafsdottir2018role}.  

\paragraph{Neural implementation}
A possible neural network implementation of these computations is shown in Fig. \ref{fig:implementation}A, which is similar to that of static PC models \citep{bogacz2017tutorial} characterized by separate populations of value and error neurons. The difference from static models is that the predictions are now from the previous time-step $k-1$. To achieve this, we assume that the value neurons are connected to the error neurons via two pathways: the direct pathway (the straight arrows between value and error neurons) and the indirect pathway through an additional population of inhibitory interneurons, which provides inhibitory inputs to the error neurons via $\bfW$. These interneurons naturally introduce a synaptic delay, such that when the inputs from step $k-1$ reach the error neurons through the indirect pathway, the error neurons are already receiving inputs from step $k$ via the direct pathway, resulting in the temporal error. In our simulation, since $\bfx_k$ are modeled as discrete and frame-by-frame inputs, the temporal delay is exactly $1$ time step. However, for real-world continuous dynamic inputs, this temporal difference will depend on the synaptic transmission delay, which is usually between $0.4$ to $4$ms \citep{katz1965measurement}. Moreover, we assume that memory recall is a much faster process than the time-steps $k$ so that the interneurons can hold a short working memory of $\mathbf{q}$ during the (iterative) inferential dynamics in Eq~\ref{eq:single-layer-recall} at step $k$, which can be achieved by the mechanisms described in \citet{barak2014working}. Notice that in this implementation, the learning rule (Eq~\ref{eq:weight-update-single-layer}) is Hebbian and the inference rule (Eq~\ref{eq:single-layer-recall}) is also local, inheriting the plausibility of static PC implementations \citep{bogacz2017tutorial}.

\begin{figure}[t]
    \centering
    \includegraphics[width=\linewidth]{figs/chap5/implementation.pdf}
    \vspace*{-3ex}
    \caption{\textbf{Neural implementations of the tPC models.} A: single-layer tPC. A single layer of value neurons $x$ makes predictions of their own future activities via a population of interneurons. Error neurons represent the temporal prediction errors. B: 2-layer tPC, where the hidden layer $z$ performs similar temporal prediction as in single-layer tPC, but also makes hierarchical, top-down predictions on $x$, similar to hierarchical predictive coding.}
    \label{fig:implementation}
\end{figure}

\subsection{2-layer tPC}
Similar to multi-layer static PC models for memory, we can have multiple layers in tPC to model the hierarchical processing of raw sensory inputs by the neocortex, before they enter the memory system \citep{salvatori2021associative,tang2023recurrent}. We focus on the 2-layer tPC model, introduced in Chapter \ref{chap:time}. In this model, we assume a set of \emph{hidden} value neurons $\mathbf{z}_k$ to model the brain's internal neural responses to the sequential sensory inputs $\mathbf{x}_k$\footnote{As mentioned in Chapter \ref{chap:time}, here we changed the notation of hidden states to $\bfz$ and observations to $\bfx$, to reflect the original latent variable formulation of predictive coding in Chapter \ref{chap:intro}.}. The hidden neurons make not only hierarchical, top-down predictions of the current activities in the sensory layer like in static PC models \citep{salvatori2021associative}, but also temporal predictions like in the single-layer tPC. We also assume that the sensory layer $\mathbf{x}_k$ does not make any temporal predictions in this case. Thus, this 2-layer tPC can be viewed as an instantiation of the hidden Markov model \citep{roweis1999unifying}.

\paragraph{Memorization}
During memorization, the 2-layer tPC tries to minimize the sum of squared errors at step $k$, with respect to the model parameters and the hidden activities:
\begin{eqnarray}
    \mathcal{F}_k(\mathbf{z}_k, \bfW, \bfF) = \Vert \mathbf{z}_k - \bfW f(\hat{\mathbf{z}}_{k-1}) \Vert_2^2 + \Vert \mathbf{x}_k - \bfF f(\mathbf{z}_k) \Vert_2^2
\end{eqnarray}
where $\bfW$ governs the temporal prediction in the hidden state, $\bfF$ is the \textbf{F}orward weight for the top-down predictions, and $\hat{\mathbf{z}}_{k-1}$ is the hidden state inferred at the previous time-step. Note that for sequential memory, no control input $\bfu$ as in Chapter \ref{chap:time} is needed. 

During memorization, the 2-layer tPC follows a similar optimization processing to that of static hierarchical PC \citep{salvatori2021associative}. It first infers the hidden representation of the current sensory input $\mathbf{x}_k$ by:
\begin{eqnarray}\label{eq:infer-z}
    \dot{\mathbf{z}}_k \propto -\frac{\partial \mathcal{F}_k(\mathbf{z}_k, \bfW, \bfF)}{\partial {\mathbf{z}}_k} = -\bm{\epsilon}^{\mathbf{z}} + f'({\mathbf{z}}_k) \odot \bfF^\top \bm{\epsilon}^{\mathbf{x}}
\end{eqnarray}
where $\odot$ denotes the element-wise product between two vectors, and $\bm{\epsilon}^{\mathbf{z}}$ and $\bm{\epsilon}^{\mathbf{x}}$ are defined as the hidden temporal prediction error $\mathbf{z}_k - \bfW f(\hat{\mathbf{z}}_{k-1})$ and the top-down error $\mathbf{x}_k - \bfF f(\mathbf{z}_k)$ respectively. After $\mathbf{z}_k$ converges, $\bfW$ and $\bfF$ are updated following gradient descent on $\mathcal{F}_k$:
\begin{eqnarray}\label{eq:learn-WhWf}
\begin{aligned}
    \Delta \bfW &\propto -\frac{\partial \mathcal{F}_k(\mathbf{z}_k, \bfW, \bfF)}{\partial \bfW} = \bm{\epsilon}^{\mathbf{z}} f(\hat{\mathbf{z}}_{k-1})^\top; \\
    \Delta \bfF &\propto -\frac{\partial \mathcal{F}_k(\mathbf{z}_k, \bfW, \bfF)}{\partial \bfF} = \bm{\epsilon}^{\mathbf{x}} f(\mathbf{z}_k)^\top
\end{aligned}
\end{eqnarray}
which are performed once for every presentation of the full sequence. The converged $\mathbf{z}_k$ is then used as $\hat{\mathbf{z}}_k$ for the memorization at time-step $k+1$.

\paragraph{Recall}
After learning/memorization, $\bfW$ and $\bfF$ are fixed. We also assume that the hidden activities $\mathbf{z}_k$ are unable to store memories, by resetting their values to randomly initialized ones. Thus, the sequential memories can only be recalled through the weights $\bfW$ and $\bfF$. Again, the sensory layer has no access to the correct patterns during recall and thus needs to dynamically change its value to retrieve the memories. The loss thus becomes:
\begin{eqnarray}
    \mathcal{F}_k(\mathbf{z}_k, \hat{\mathbf{x}}_k) = \Vert \mathbf{z}_k - \bfW f(\hat{\mathbf{z}}_{k-1}) \Vert_2^2 + \Vert \hat{\mathbf{x}}_k - \bfF f(\mathbf{z}_k) \Vert_2^2
\end{eqnarray}
where $\hat{\mathbf{x}}_k$ denotes the activities of value neurons in the sensory layer during recall. Both the hidden and sensory value neurons are updated to minimize the loss. The hidden neurons will follow similar dynamics specified in Eq.~\ref{eq:infer-z}, with the top-down error $\bm{\epsilon}^{\mathbf{x}}$ defined as $\hat{\mathbf{x}}_k - \bfF f(\mathbf{z}_k)$, whereas the sensory neurons are updated according to:
\begin{eqnarray}\label{eq:infer-x}
    \dot{\hat{\mathbf{x}}}_k \propto -\frac{\partial \mathcal{F}_k(\mathbf{z}_k, \hat{\mathbf{x}}_k)}{\partial \hat{\mathbf{x}}_k} =  -\bm{\epsilon}^{\mathbf{x}}
\end{eqnarray}
and the converged $\hat{\mathbf{x}}_k$ is the final retrieval. Similar to the single-layer case, if the converged $\hat{\mathbf{z}}_k$ is used for the recall at the next step directly, the recall is offline; on the other hand, if we query the model with $\mathbf{q} = \mathbf{x}_k$ i.e., the ground-truth and use the query to infer $\hat{\mathbf{z}}_k$, and then use $\hat{\mathbf{z}}_k$ for the recall at the next step, the recall is online.

\paragraph{Neural implementation}
A neural implementation of the computations above is shown in Fig.~\ref{fig:implementation}B. The hidden layer follows the same mechanism in the single-layer tPC, with interneurons introducing a synaptic delay for temporal errors and short-term  memory to perform the inferential dynamics (Eq.~\ref{eq:infer-z}). The connection between the hidden layer and the sensory layer $\bfF$ is modeled in the same way as in static PC models, which requires only Hebbian learning and local computations \citep{bogacz2017tutorial}. Note that this implementation is essentially the same as Fig.~\ref{fig:recurrent_multistep}A, although the neurons storing the inference result $\hat{\bfz}_{k-1}$ have a more specific neuron type i.e., interneurons. The memorization and recall pseudocode for the tPC models is provided in Appendix \ref{app:seqmem}.

\section{Results}

\subsection{Theoretical relationship to AHNs}
We first develop a theoretical understanding of single-layer tPC by relating it to AHNs:
\begin{theorem}\label{theorem1}
    Assume, without loss of generality, a sequence of memories $\mathbf{x}_k\in \mathbb{R}^N$ ($k=1,...,K+1$) with zero mean. With an identity nonlinear function $f(x)=x$ in Eq.~\ref{eq:single-layer-energy}, the retrieval of the single-layer tPC with query $\mathbf{q}$, defined as $R^{tPC}(\mathbf{q})$, can be written as:
    \begin{eqnarray}\label{eq:tpc-recall}
        R^{tPC}(\mathbf{q}) =  \sum_{k=1}^K \mathbf{x}_{k+1}(\bfM\mathbf{x}_k)^\top \bfM\mathbf{q}
    \end{eqnarray}
    where $M$ is an empirical whitening matrix such that:
    \begin{eqnarray}
        \langle \bfM\mathbf{x}_k (\bfM\mathbf{x}_k)^\top\rangle_k = \bfI_N
    \end{eqnarray}
    where $\langle\cdot\rangle_k$ is the expectation operation over $\mathbf{x}_k$'s. 
\end{theorem}
Proof of this property is provided in Appendix \ref{app:seqmem}. Essentially, this property implies that our single-layer tPC, in its linear form, can be regarded as a special case of the UHN for sequential memories (Eq.~\ref{eq:UHN-retrieval}), with a ``whitened dot product'' similarity function where the two vectors $\mathbf{x}_k$ and $\mathbf{q}$ are first normalized and decorrelated (to have identity covariance $\bfI_N$) before the dot product. AHNs, on the other hand, calculate the dot product directly (due to its different energy function structure to tPC, as shown in Appendix \ref{app:seqmem}). Biologically, this property provides a possible mechanism of statistical whitening in the brain that, unlike earlier models of biological whitening with explicit objectives \citep{pehlevan2019neuroscience,golkar2022constrained,duong2023statistical}, performs this computation \emph{implicitly} via the circuit shown in Fig.~\ref{fig:implementation} that minimizes the temporal prediction errors.


\subsection{Experimental comparison to AHNs}
\begin{figure}[t]
    \centering
    \includegraphics[width=\linewidth]{figs/chap5/binary.pdf}
    \caption{\textbf{Comparison between single-layer tPC and AHNs.} A: Capacity of models with uncorrelated binary patterns. B: Capacity of models with binary patterns with increasing feature correlations. C: Recall performance with sequences of binary MNIST digits.}
    \label{fig:binary}
\end{figure}
To understand how the whitening step affects the performance in sequential memory tasks, we compare our single-layer tPC with the family of AHNs exeperimentally. To ensure consistency to Property \ref{theorem1} above, we use an identity nonlinearity $f(x)=x$ for all these experiments. Empirically, we found that using a $\texttt{tanh}$ nonlinearity makes subtle differences irrelevant to our main discussion in this chapter, and we discuss it in Appendix \ref{app:seqmem}.
% \vspace{-1ex}
\paragraph{Polynomial AHNs}
% To understand how this whitening step affects the performance in sequential memory tasks, we compared our single-layer tPC with an identity $f(\cdot)$ to AHNs with different degrees $d$ (Eq.~\ref{eq:recall-MAHN}). 
We first compare tPC with polynomial AHNs (Eq.~\ref{eq:recall-MAHN}) in sequences of uncorrelated binary patterns,  where AHNs are known to work well \citep{sompolinsky1986temporal,chaudhry2023modern}. We plot their sequence capacity $P_{max}$ against the number of value neurons of the models i.e., the pattern dimension $N$. Here, $P_{max}$ is defined as the maximum length of a memorized sequence, for which the probability of incorrectly recalled bits is less than or equal to $0.01$. Fig.~\ref{fig:binary}A shows that the capacity of our single-layer tPC is greater than that of the original AHN ($d=1$) but smaller than that of a quadratic AHN ($d=2$). Notice that the single-layer tPC has an identity $\sep$ function like the original AHN. Therefore the whitening operation has indeed improved the performance of the dot product $\simi$ function. Inspired by the decorrelation effect of statistical whitening, we then generated binary patterns with $N=100$ \emph{correlated} features, with a parameter $b$ controlling the level of correlation ($b=|\sqrt{\text{correlation}}|$). The approach that we followed to generate the correlated patterns is provided in Appendix \ref{app:seqmem}. As shown in Fig.~\ref{fig:binary}B, as the correlation increases, all AHNs up to $d=3$ suffer from a quick decrease of capacity $P_{max}$, whereas the capacity of single-layer tPC almost remains constant. This observation is consistent with the theoretical property that the whitening transformation essentially decorrelates features such that patterns with any level of correlation are regarded as uncorrelated in tPC recall (Eq.~\ref{eq:tpc-recall}). This result also explains the comparison in Fig.~\ref{fig:binary}A: although the patterns generated in this panel are theoretically uncorrelated, the small correlation introduced due to experimental randomness will result in the performance gap between AHN and single-layer tPC.

We then investigate the performance of these models with sequences of binarized MNIST images \citep{lecun2010mnist} in Fig.~\ref{fig:binary}C. It can be seen that the AHNs with $d=1$ and $d=2$ quickly fail as the sequence length $P$ reaches $3$, whereas the single-layer tPC performs well. These results suggest that our tPC with a whitening step is superior to simple AHNs due to the inherently correlated structure of natural inputs such as handwritten digits. For all the experiments with binary patterns, we used the online recall mentioned above, and polynomial AHNs already fail in this simpler recall scenario.


% \subsection{Comparison to MCAHN}
\paragraph{MCAHN}
Due to the quick failure of AHNs with a polynomial $\sep$ function, we now compare our single-layer tPC with the MCAHN (Eq.~\ref{eq:recall-MCAHN}). In static memory tasks, it is known that the $\softmax$ separation leads to exponentially high capacity, especially when $\beta$ is high \citep{demircigil2017model,millidge2022universal}. In this chapter we use $\beta=5$ for all MCAHNs. We first compare the performances of our single-layer tPC model 
% (with identity $f(\cdot)$) 
and an MCAHN on random sequences of MNIST digits with varying lengths. Here we trigger recalls with online queries. Fig.~\ref{fig:continuous}A shows that the performance of our single-layer tPC, measured as the mean squared error (MSE) between the recalled sequence and the ground truth,  is better than that of the MCAHN, further demonstrating the usefulness of the implicit whitening in our model.

\begin{figure}[t]
    \centering
    \includegraphics[width=0.9\linewidth]{figs/chap5/continuous.pdf}
    \caption{A: Recall MSE of MNIST sequences with increasing length; B: Recall MSE of MovingMNIST sequences of a fixed length $10$ but with an increasing number of sequences. Error bars obtained with $5$ seeds.}
    \label{fig:continuous}
\end{figure}

\begin{figure}[t]
    \centering
    \includegraphics[width=0.98\linewidth]{figs/chap5/continuous2.pdf}
    \caption{\textbf{Visual results of offline memory recall with $3$ datasets.} A: MovingMNIST. B: CIFAR10. C: UCF101.}
    \label{fig:continuous2}
\end{figure}

Despite the superior performance of our model in this task, we note that random sequences of MNIST images are not naturally sequential inputs i.e., there are no sequential dynamics underlying them. We thus examine the models on the MovingMNIST dataset \citep{srivastava2015unsupervised}. Each video in this dataset consists of $20$ frames of $2$ MNIST digits moving inside a $64\times 64$ patch. Due to the fixed sequence length, for experiments with MovingMNIST we vary the total number of sequences to memorize and fix the sequence length to the first $10$ frames of the videos.  The performance of the models is shown in Fig.~\ref{fig:continuous}B. On average, the recall MSE of MCAHN has a slower increase than that of the single-layer tPC as the total number of sequences increases. However, the performance of MCAHN has very large variations across all sequence numbers. To probe into this observation, we visually examined $3$ examples of the MovingMNIST movies recalled by MCAHN and our single-layer tPC in Fig.~\ref{fig:continuous2}A, when the total number of sequences to memorize is $40$. MCAHN produces very sharp recalls for the first $2$ example sequences, but totally fails to recall the third one by converging to a different memory sequence after the red triangle in Fig.~\ref{fig:continuous2}A. On the other hand, the recall by single-layer tPC is less sharp but stably produces the correct sequence. This phenomenon can be understood using the UHN framework \citep{millidge2022universal}: in Eq.~\ref{eq:recall-MCAHN}, when $\beta$ is large, the $\softmax$ separation function used by MCAHN will assign a weight close to $1$ to the memory whose preceding frame is most similar to $\mathbf{q}$ (measure by dot product), and weights close to $0$ to all other memories, which results in the sharp recall. In contrast, our single-layer tPC model uses an identity separation function that fails to suppress the incorrect memories, resulting in blurry recalls. Importantly, however, the failure of MCAHN in sequence $3$ in Fig.~\ref{fig:continuous2}A suggests that there are ``strong attractors'' in the memories with an undesirable advantage in dot product similarity which resulted in the large variance in the numerical results, and is addressed by the whitening step in single-layer tPC as it effectively normalized the patterns before dot product.

The importance of whitening in tPC is further demonstrated in our experiments with random sequences of CIFAR10 \citep{krizhevsky2009learning} images and movies from the UCF101 \citep{soomro2012ucf101} dataset, shown in Figs.~\ref{fig:continuous2}B and C. When recalling these colored sequences, MCAHN can easily converge to strong attractors preceded by frames with many large pixel values that lead to large dot products e.g., the third image in the CIFAR10 example with bright backgrounds, and the penultimate frame in the UCF101 example with a large proportion of sand, which give their subsequent frames large similarity scores. This problem is consistent with earlier findings with static memories \citep{salvatori2021associative}, and is circumvented in our single-layer tPC model with the whitening matrix $\bfM$ normalizing the pixel values across the sequence, yielding the correct and more stable memory recalls. However, they are less sharp due to the identity separation function. For all the experiments in Fig.~\ref{fig:continuous}B and Fig.~\ref{fig:continuous2}, we used offline recall to make the tasks more challenging and more consistent with reality. Results with online recalls are shown in Appendix \ref{app:seqmem}.

\subsection{Comparison to behavioral data in sequential memory experiments}
\begin{figure}[t]
    \centering
    \includegraphics[width=0.97\linewidth]{figs/chap5/behavior.pdf}
    \caption{\textbf{Replicating behavioral data with tPC.} A: Experimental data from \citet{crannell1957comparison} that studies the impact of sequence length on serial recall of English words and the replications by \citet{botvinick2006short} and tPC. B: tPC replicates the primacy/recency effects in serial recall experiments \citep{henson1998short}.}
    \label{fig:behavior}
\end{figure}

We further demonstrated the biological relevance of tPC by comparing it to data from behavioral experiments in sequential memory. In Fig~\ref{fig:behavior}A, our 2-layer tPC is compared with \citet{crannell1957comparison} study on sequence length's impact on serial recall of English words. Using one-hot vectors to represent letters (i.e., each ``word'' in our experiment is an ordered combination of one-hot vectors of ``letters'', a minimal example of a word with 3 letters being: $[0,1,0], [1,0,0], [0,0,1]$), we demonstrate accuracy as the proportion of perfectly recalled sequences across varying lengths. Our model aligns consistently with experimental data in \citet{crannell1957comparison} as well as the recurrent network model by \citet{botvinick2006short}, displaying a sigmoidal accuracy drop with increasing sequence length.

Fig~\ref{fig:behavior}B introduces a qualitative comparison to \citet{henson1998short} experimental data, examining primacy/recency effects in serial recall of letters. These effects involve higher accuracy in recalling early (primacy) and late (recency) entries in a sequence, with the recency effect slightly weaker than the primacy effect. Using one-hot vectors and a fixed sequence length $7$ ($6$ positions are shown as the first position is given as the cue to initiate recall in our experiment), we visualize recall frequency at different positions across simulated sequences (100 repetitions, multiple seeds for error bars). Each bar in Fig~\ref{fig:behavior}B indicates the frequency of an entry at a particular position being recalled at each position. Our 2-layer tPC reproduces primacy/recency effects, albeit weaker than the model in \citet{henson1998short} and previous models \citep{botvinick2006short}. Additionally, the model tends to recall neighboring entries upon errors, echoing Henson's data. We attribute the weaker effects to tPC's memory storage in weights, which leads to overall improved performance across positions. Details for these experiments are shown in Appendix \ref{app:seqmem}.

\subsection{tPC develops context-dependent representations}

\begin{figure}[t]
    \centering
    \includegraphics[width=\linewidth]{figs/chap5/aliased_generalization.pdf}
    \caption{\textbf{Context representation and generalization of tPC.} A: A simple aliased example with MNIST. B: Numerical investigation into the impact of aliased or repeating elements on model performance. C: Different latent representations of aliased inputs by the 2-layer tPC. D/E: Recall/generalization of sequences with rotational dynamics. ``GT'' stands for ground truth and $16$ and $1024$ are the numbers of training sequences. F: Recall and generalization MSE of seen and unseen rotating MNIST images. Error bars obtained with $5$ seeds.}
    \label{fig:aliased}
\end{figure}

In Fig.~\ref{fig:continuous}, we plotted the recall MSE of the 2-layer tPC model in MovingMNIST, which is similar to that of the single-layer tPC. 
% We chose the size of the hidden layer $\mathbf{z}$ in the 2-layer tPC so that the total number of parameters of these two models is approximately the same (exact sizes provided in SM).
The close performance of these models raises the question of whether and when the hidden layer and hierarchical processing of sequential inputs are necessary. Inspired by earlier neuroscience theories that the hippocampus develops neuron populations signaling the sensory inputs and the context of the inputs separately \citep{eichenbaum2014time,wallenstein1998hippocampus}, we hypothesize that the hidden neurons in our model represent \emph{when} an element occurs in a memory sequence i.e., its context.
% Inspired by the ``perceptual aliasing'' problem in neuroscience \citep{whitehead1991learning,rao1999optimal},
We thus designed a sequential memory task with aliased, or repeating inputs at different time-steps \citep{whitehead1991learning,rao1999optimal}. An example of such an aliased sequence can be seen in Fig.~\ref{fig:aliased}A, where the second and the fourth frames of a short MNIST sequence are exactly the same (``$2$''). Recalling such a sequence is inherently more challenging as the models have to determine, when queried with the ``$2$'' during recall (either online or offline), whether they are at the second or the fourth step to give the correct recall at the next step (``1'' or ``3''). As can be seen in Fig.~\ref{fig:aliased}A, both MCAHN (which can be regarded as a single-layer network \citep{millidge2022universal}) and single-layer tPC fail in this task, recalling an average frame of  ``1'' and ``3'' after the aliased steps, whereas the 2-layer tPC can recall the correct sequence. We then conducted a numerical investigation into this problem. We first plotted the (online) recall MSEs of the single- and 2-layer tPC models in random MNIST sequences (sampled from the training set) of varying lengths, which are shown as the solid lines in Fig.~\ref{fig:aliased}B. We then randomly replaced $20\%$ (rounded up to the closest integer) of the elements in these sequences with a single digit from the test set of MNIST so that each sequence now has $20\%$ repeating i.e., aliased elements, and plotted the recall MSEs as the dotted lines in Fig.~\ref{fig:aliased}B. The result suggests that sequences with aliased inputs affect the single-layer model much more than it affects the 2-layer one, producing significantly larger MSEs than recalls without aliased inputs. It is worth noting that aliased inputs are ubiquitous in natural sequential memories. In Appendix \ref{app:seqmem}, we provide a natural example from the UCF101 dataset where the 2-layer tPC successfully de-aliased repeating inputs whereas the MCAHN and single-layer tPC failed.
% An example of a naturally aliased sequential input is shown in Fig.~\ref{fig:aliased}C, where we trained the models to memorize a sequence from the ``push-up'' class from the UCF101 dataset. The circled time-steps $2$ and $5$ are approximately aliased, although step $2$ is captured when the person is going up, whereas step $5$ is captured when he is going down. The MCAHN and single-layer tPC again recalled average frames whereas the 2-layer tPC successfully disambiguated the aliased inputs and recalled the correct next frames.

% In all the experiments above we tuned the hidden size of the 2-layer models so that they have roughly the same number of parameters as the single-layer models. This results in high-dimensional hidden states that are hard to analyze directly. Thus, to 
To further understand the mechanism underlying the 2-layer tPC with aliased memories, we used a simpler synthetic sequential memory shown in Fig.~\ref{fig:aliased}C bottom, where a white bar moves first down and then up in a $5\times 5$ frame so that the steps $2$ and $4$ are aliased \citep{rao1999optimal}. We then trained a 2-layer tPC with a hidden size $5$ to memorize this sequence and queried it offline. The smaller hidden size allows us to plot, when the recall dynamics (Eq.~\ref{eq:infer-z}) have converged, the exact hidden activities in Fig.~\ref{fig:aliased}C top, where each vertical line represents the activity of a hidden value neuron $\hat{\mathbf{z}}_k$. As can be seen in the circled time-steps, the 2-layer model represents the aliased inputs differentially in its hidden states, which helps it recall the next frame correctly. This property is consistent with early observations in neuroscience that when memorizing sequences, the hippocampus develops a conjunction of neurons representing individual inputs, as well as neurons signaling the temporal context within which an individual appears \citep{eichenbaum2014time,wallenstein1998hippocampus}. In our simple 2-layer model, the ``sensory'' layer represents individual inputs, whereas the hidden layer plays the role of indexing time and context.

\subsection{tPC generalizes learned dynamics to unseen sequences}

After memorizing a large number of training sequences sharing underlying dynamics, can tPC generalize the dynamics to unseen sequences? In this experiment, we train the 2-layer tPC with sequences of rotating MNIST digits of identical rotating dynamics (i.e., the digits are rotating towards a fixed direction with a fixed angle at each time step) and vary the number of training sequences (“training size”). An example of these rotating MNIST digits can be seen in Fig~\ref{fig:aliased}D, row “ground truth”. The model's performance is assessed by its ability to rotate both seen MNIST digits and unseen EMNIST letters. For small training sizes (16), tPC can recall seen rotating digits but struggles with generalizing to unseen letters (Fig~\ref{fig:aliased}D and E, second row). Increasing the training size to 1024 improves generalization, evident in clearer rotating sequences (Fig~\ref{fig:aliased}D and E, bottom row). Panel F quantitatively confirms this trend: the generalization MSE on unseen EMNIST drops as MNIST training size increases, indicating the model learns the underlying dynamics. Interestingly, the recall MSEs for seen MNIST sequences also decrease due to the model extracting rotational dynamics from the larger training set, differing from the behavior observed in random MNIST sequences (Fig~\ref{fig:continuous}A). Generalization and the capability of developing contextual representations that disambiguate aliased inputs are two critical functions underlying the flexible behavior of animals, thus connecting our tPC to models of cognitive maps in the hippocampus and related brain regions \citep{whittington2020tolman}.

\section{Discussion}

\subsection{Summary}
Inspired by experimental and theoretical discoveries in neuroscience, in this chapter we have examined tPC models in sequential memory tasks. We have shown that our tPC model can memorize and recall sequential inputs such as natural movies, and performs more stably than earlier models based on Asymmetric Hopfield Networks. We have also provided a theoretical understanding of the stable performance of the tPC model, showing that it is achieved by an additional statistical whitening operation that is missing in AHNs. Importantly, this whitening step is achieved implicitly by a plausible neural circuit performing local error minimization. Moreover, 
% the architectural flexibility of PC models has allowed us to examine the necessity of hierarchical processing of sequential memories via 
our 2-layer tPC has exhibited representational and behavioral properties consistent with biological observations, including contextual representations and generalization. Overall, our model has not only provided a possible neural mechanism underlying sequential memory in the brain but also suggested a close relationship between PC and HN, two influential computational models of biological memories. Future directions include 
% quantitative comparisons to experimental data, as well as
systematic investigations into tPC with more than $2$ layers and modelling cognitive maps with tPC.

\subsection{Relationship to AHNs}
In this chapter we have established a formal relationship between the retrieval functions of single-layer tPCN and AHN. We also demonstrated that tPC outperforms AHN with a linear separation function but under-performs AHN with a polynomial separation function. An interesting question is thus whether there exists an analytical expression for the capacity of tPCN in sequential memory, similar to what was derived for AHNs in \citet{chaudhry2023modern}.

\subsection{Relationship to other models of sequential memory}
In addition to using Hopfield Networks for sequential memory, other models are rooted in anatomical and physiological observations. Models such as those proposed by \citet{jensen1996physiologically} and \citet{mehta2000experience} suggest hippocampal sequential memory encoding via neuronal firing chains. Other frameworks highlight the role of contextual representations in sequential memory \citep{wallenstein1998hippocampus,levy1989computational}, successfully reproducing phenomena such as the recency and contiguity effects observed in free recall experiments \citep{howard2002distributed}. Recurrent spiking network models also exhibit sequential memory capabilities \citep{eliasmith2012large}. However, unlike predictive coding, these models do not operate under a unified computational framework—namely the Bayesian Brain hypothesis—that could be generalized across different brain regions. Nevertheless, it would be interesting to investigate if properties replicated in these physiologically more realistic models can naturally arise as a result of performing Bayesian inference via predictive coing. Broadly, aligning predictive coding models more closely with anatomical and neurophysiological structures supporting sequential memory remains a promising direction for future exploration.


