Transformers Learn Variable-order Markov Chains in-Context

## Abstract

Abstract Large language models (LLMs) have demonstrated impressive in-context learning (ICL) capability. However, it is still unclear how the underlying transformers accomplish it, especially in more complex scenarios. Toward this goal, several recent works studied how transformers learn fixed-order Markov chains (FOMC) in context, yet natural languages are more suitably modeled by variable-order Markov chains (VOMC), i.e., context trees (CTs). In this work, we study the ICL of VOMC by viewing language modeling as a form of data compression and focusing on small alphabets and low-order VOMCs. This perspective allows us to leverage mature compression algorithms, such as context-tree weighting (CTW) and prediction by partial matching (PPM) algorithms as baselines, the former of which is Bayesian optimal for a class of priors that we refer to as the CTW priors. We empirically observe a few phenomena: 1) Transformers can indeed learn to compress VOMC in-context, while PPM suffers significantly; 2) The performance of transformers is not very sensitive to the number of layers, and even a two-layer transformer can learn in-context quite well; and 3) Transformers trained and tested on non-CTW priors can significantly outperform the CTW algorithm. To explain these phenomena, we analyze the attention map of the transformers and extract two mechanisms, on which we provide two transformer constructions: 1) A construction with D + 2 𝐷 2 D+2 italic_D + 2 layers that can mimic the CTW algorithm accurately for CTs of maximum order D 𝐷 D italic_D , 2) A 2-layer transformer that utilizes the feed-forward network for probability blending. These constructions can explain most of the phenomena mentioned above. One distinction from the FOMC setting is that a counting mechanism appears to play an important role. We implement these synthetic transformer layers and show that such hybrid transformers can match the ICL performance of transformers, and more interestingly, some of them can perform even better despite the much-reduced parameter sets.

## 1 Introduction

Large language models (LLMs) are capable of completing various tasks [, , , ]. The transformer model [], the key behind current prevailing LLMs, is known to have strong in-context learning (ICL) capabilities, and concrete ICL results for transformers have been established for some simple tasks [, , , ]. Despite these results, the mechanism for transformers to learn in context is still not fully understood, especially when the scenario is complex or the sequences have memories. Toward this goal, several recent works studied how transformers can learn fixed-order Markov chains (FOMCs) either in training or in-context [, ], where insightful observations and theoretical results were obtained. The FOMC is however a poor match for natural languages, for which variable-order Markov chains (VOMCs), also known as context tree (CT) models [, ], are often viewed as a more suitable model [].

In another related line of research on LLMs, several recent works made explicit the close connection between language models and data compression [, ], the latter of which was aptly titled “Language Modeling Is Compression”. Indeed, despite their difference in the eventual applications, the key driver behind both is an accurate (auto-regressive) probability distribution estimator. We adopt this perspective and use the compression rates in a fixed context window as our main evaluation metric. This allows us to use several well-known compression algorithms, such as prediction by partial matching (PPM) [] and context weighting algorithms (CTW) [], as baselines. In particular, the CTW algorithm is Bayesian optimal under certain priors, which gives us a fundamental lower bound in such settings.

In this work, we consider the ICL of VOMCs from the data compression perspective and refer to this task as ICL-VOMC. The VOMC sources have finite memory, however, each new symbol may depend on different numbers of previous symbols, i.e., the length of the memory may vary. We emphasize that ICL-VOMC is considerably more complex than ICL of FOMCs. A naive strategy would be to view a VOMC as an FOMC of the largest possible order, which however leads to highly inefficient ICL, since the in-context samples are not utilized well. The PPM algorithms can be viewed as an approximate surrogate with this naive approach in the small alphabet setting we consider.

We first train a set of shallow transformers of various numbers of layers for VOMCs of various maximum orders, and empirically observe a few phenomena: 1) Transformers can indeed learn to compress VOMC in context, while PPM suffers significantly; 2) The performance of transformers is not very sensitive to the number of layers, and even a two-layer transformer can learn in-context quite well, tracking the CTW performance closely; and 3) Transformers trained and tested on non-CTW-priors can significantly outperform the CTW algorithm. To explain these phenomena, we carefully analyze the attention maps of the transformers, and discover two attention mechanisms, which form suffixes and perform suffix matching, respectively. Equipped with these mechanisms, we answer the question of whether transformers have the modeling capability to mimic the CTW algorithm. One difficulty is that the CTW algorithm has a recursive structure, which is not directly compatible with the transformer architecture. We first propose an alternative algorithm representation, based on which a transformer construction with $D+2$ layers is proposed, that can mimic CTW accurately for CTs of maximum order $D$. This establishes a fundamental capability of transformers for ICL-VOMC. The alternative representation enjoys an intuitive interpretation as blending probability estimates along a path on the context tree.

The CTW algorithm relies heavily on counting the occurrences of suffixes of varying lengths to determine the blending coefficients, and a significant component of our transformer construction is for such counting in the second layer. Given its importance, we postulate that 2-layer transformers perform well because such information already allows close-to-optimal blending. We propose such a simple 2-layer transformer, by providing one feed-forward (FF) layer with the probability estimates and the corresponding counts directly. The FF layer’s role then largely reduces to approximating the proper blending coefficients. We implement several synthetic transformer layers and show that the hybrid transformers can mostly match the ICL performance of transformers. This construction provides an explanation for 2-layer transformers to perform well in ICL-VOMC, and also for the superior performance on non-CTW-priors. More interestingly, some of these synthetic transformers can perform even better despite the much-reduced parameter sets.

Main Contributions: We believe that ours is the first study of ICL for VOMC, and the contributions are summarized as follows. (i) We demonstrate that transformers can indeed (numerically) learn to compress VOMC in-context, close to optimal CTW algorithm for appropriate CTW-prior. (ii) We show that transformers can outperform CTW when trained and tested on non-CTW-priors. (iii) We give an explicit $D+2$-layer transformer construction to imitate CTW establishing its capabilities, based on a novel Bayesian optimal next token prediction representation, which can be of independent interest. (iv) Our construction allows us to investigate the relative insensitivity to the number of layers, of the transformer performance, *i.e.,* even $2$-layer transformers perform well. It also gives partial explanations of the ICL capabilities of transformers on VOMC.

### 1.1 Related works

There have been many efforts in studying the ICL capabilities of transformers. A significant recent development is the elucidation of the connection to gradient descent, particularly for linear regression tasks [, , , ]. [] formulated the ICL problem as a multi-task learning problem and considered ICL for several simple problem settings for which the authors provide risk bounds for ICL of supervised learning algorithms in these problem settings. [] viewed the ICL problem as a meta-learner and studied the relation between tasks and model sizes. These lines of approaches focused on the ICL of supervised learning tasks, such as classification and regression, while this work belongs to another direction of studying ICL for the next token prediction of some unknown underlying dynamics.

[] studied the induction head, i.e., the forming of small $k$-gram attention in LLMs. [] studied the balance between ICL and in-weight learning, and observed the abrupt emergence of the induction head corresponds to the emergence of ICL. The induction head was generalized to the statistical induction head in [] mainly to study bigrams. We adopted it but further allowed more statistical induction heads for more suffixes to be included together, in the first two layers of the idealized transformer.

There have also been efforts to study transformers and learning of Markov chains. [] viewed ICL as a Bayesian inference problem, where a latent concept determines an HMM, and the observations from the HMM can lead to the identification of the hidden concept. They studied the eventual ICL capability, i.e., when the number of in-context examples goes to infinity. [] studied the limitations of transformer on learning to perform belief inference for HMMs sources compared to recurrent neural networks. The work in [] allowed a fixed-order Markov chain to switch to a new deterministic mode, and the authors study the training behavior of the corresponding ICL task with this mode transition. [] made a comprehensive empirical comparison of various language models on random finite automata, and showed that the transformer performs the best among these models. [] studied the loss landscape during transformer training on sequences generated from a single fixed-order Markov chain, using a single-layer transformer. Their study does not consider ICL. More recently [] considered ICL of FOMCs with single-head transformers, and provided a construction to show that it is possible to use a single attention head to capture longer memory in the sequence.
The work most relevant to us is [], where ICL of a fixed-order Markov chain was considered, and the training behavior was studied both empirically and theoretically, and the forming of induction heads in a two-layer network was demonstrated. All these existing works assumed fixed-order Markov models or fixed-order HMMs, usually with orders kept at 1 or 2; moreover, they almost all focus on the emergence of the induction heads during training or the training landscape. Our study is different firstly in the variable-order nature of the Markov models, and secondly the focus on the on-time ICL performance instead of the training landscape and behavior.

Lossless data compression has a long history, with many different algorithms being developed over the years. The most popular general-purpose compression algorithms are perhaps the Lempel-Ziv compression algorithms [, ] and their variants, which belong to dictionary-based compression algorithms. These algorithms do not explicitly maintain any probabilistic models, and their efficiency comes from maintaining an efficiency dictionary of sequences that have been seen before, and to be matched with future sequences. More powerful compression algorithms usually maintain probability models explicitly, which are then plugged into an AC module [, , ] for efficient compression. The most well-known classes of algorithms in this category is the context-tree weighting algorithm [, , ] and prediction by partial matching []. The former enjoys a strong theoretical guarantee, particularly on binary sources [], but has some difficulty in its practical implementation [, , , ], particularly for large alphabet sizes and sequential data. The latter is based more on heuristics, and has been improved and extended in various ways [, , ]. Methods based on probabilistic modeling are usually more resource-extensive, though they have gained more popularity recently due to the increased availability of computing resources. The evaluation given in [] suggests that CTW and PPM are the two most powerful compression algorithms in practice. There are other compression algorithms such as those based on the Burrows-Wheeler transformation [] which do not explicitly maintain a probabilistic model, but are also not dictionary-based.

## 2 Preliminaries

Notation: Scalars, symbols, and strings are denoted by italic letters like $n,N$, $x$, and $s$. Denote by string $x_{i}^{j}:=(x_{i},x_{i+1},\ldots,x_{j})$ as a sequence of symbols. Define $()$ or $x_{i}^{j}$ with $i>j$ as an empty string. Vectors and matrices are in bold like $\mathbf{x}$, $\mathbf{H}$, and sets in calligraphic like $\mathcal{A}$ with cardinally $|\mathcal{A}|$.

### 2.1 The Transformer Model

Transformer interacts with sequential data, e.g., $x_{1}^{N}=(x_{1},\ldots,x_{N})$, where token $x_{i}$ is a symbol from an alphabet (a.k.a. vocabulary) $\mathcal{A}$ with $A=|\mathcal{A}|$. Each token $x_{i}$ is embedded into $\mbox{$\mathbf{h}$}^{(1)}_{i}\in\mathbb{R}^{E}$ by integrating the information of its value $x_{i}$ and position $i$, where $E$ is the embedding dimension.

We introduce an $L$-layer decoder-only transformer model. Each layer of the transformer takes matrix $\mbox{$\mathbf{H}$}^{(\ell)}=[\mbox{$\mathbf{h}$}^{(\ell)}_{1},\mbox{$\mathbf{
h}$}^{(\ell)}_{2},\ldots,\mbox{$\mathbf{h}$}^{(\ell)}_{N}]$, where $\mbox{$\mathbf{h}$}_{i}^{(\ell)}\in\mathbb{R}^{E}$, as its input and applies the multi-head attention (MHA) layer operation and the feed-forward layer operation, and the output of the layer is the input to the next layer, denoted as $\mbox{$\mathbf{H}$}^{(\ell+1)}$. The decoder-only multi-head attention layer with $M^{(\ell)}$ heads is

$$ $\displaystyle\mbox{$\mathbf{a}$}_{i}^{(\ell)}=\text{MHA}\left(\mbox{$\mathbf{h _{i}}$},\mbox{$\mathbf{H}$};\{W_{O,m}^{(\ell)},W_{Q,m}^{(\ell)},W_{K,m}^{(\ell )},W_{V,m}^{(\ell)}\}_{m=1}^{M^{(\ell)}}\right)\triangleq W_{O}^{(\ell)}\left[ \mbox{$\mathbf{b}$}_{1,i}^{(\ell)};\mbox{$\mathbf{b}$}_{2,i}^{(\ell)};\ldots; \mbox{$\mathbf{b}$}_{M^{(\ell)},i}^{(\ell)}\right],$ (1) $$

where $\{W_{Q,m}^{(\ell)},W_{K,m}^{(\ell)},W_{V,m}^{(\ell)}\}_{m=1}^{M^{(\ell)}}$ are the $E^{(\ell)}\times E$ query matrices, key matrices, and value matrices(^1^11In practice, embedding dimension $E$ is divisible by the number of heads $M^{(\ell)}$ and $E=M^{(\ell)}E^{(\ell)}$.) at the $\ell$-th layer and $m$ is the index of the attention head, respectively, $W_{O}^{(\ell)}$ is the $E\times(M^{(\ell)}E^{(\ell)})$ output mapping matrix, and $\mbox{$\mathbf{b}$}_{m}^{(\ell)}$ is the output of the $m$-th attention head at this layer defined as

$$ $\displaystyle\mbox{$\mathbf{b}$}_{m,i}^{(\ell)}=(W_{V,m}^{(\ell)}[\mbox{$ \mathbf{h}$}_{1}^{(\ell)},\mbox{$\mathbf{h}$}_{2}^{(\ell)},\ldots,\mbox{$ \mathbf{h}$}_{i}^{(\ell)}])\cdot\text{softmax}((W^{(\ell)}_{K,m}[\mbox{$ \mathbf{h}$}^{(\ell)}_{1},\mbox{$\mathbf{h}$}^{(\ell)}_{2},\ldots,\mbox{$ \mathbf{h}$}^{(\ell)}_{i}])^{\top}(W^{(\ell)}_{Q,m}\mbox{$\mathbf{h}$}^{(\ell) }_{i})),$ (2) $$

where we used “;” to indicate vertical matrix concatenation and “,” to indicate horizontal matrix concatenation. The attention layer has a residual connection, and the attention output together with the residual connection also goes through a feed-forward layer with a residual connection

$$ $\displaystyle\mbox{$\mathbf{h}$}_{i}^{(\ell+1)}=\text{FF}(\mbox{$\mathbf{a}$}_ {i}^{(\ell)};W^{(\ell)}_{1},W^{(\ell)}_{2})=W^{(\ell)}_{1}\sigma(W^{(\ell)}_{2 }(\mbox{$\mathbf{a}$}^{(\ell)}_{i}+\mbox{$\mathbf{h}$}_{i}^{(\ell)}))+(\mbox{$ \mathbf{a}$}^{(\ell)}_{i}+\mbox{$\mathbf{h}$}^{(\ell)}_{i}),$ (3) $$

where $\sigma$ is a non-linear activation function (e.g., ReLU or sigmoid). The output of the last ($L$-th) transformer layer $\mbox{$\mathbf{H}$}^{(L+1)}$ goes through a linear then softmax unit to predict the probability of generating the next symbol in vocabulary $\mathcal{A}$ based on the past observations:

$$ $\displaystyle\hat{\mbox{$\mathbf{p}$}}_{i+1}=\text{softmax}(W^{(L+1)}_{O}\mbox {$\mathbf{h}$}_{i}^{(L+1)})\in\Delta_{A},\quad i=1,\ldots,N-1,$ (4) $$

where $\Delta_{A}$ is the probability simplex on $\mathcal{A}$. The transformer model is illustrated by Fig. 1.

Figure: Figure 1: Transformer model
Refer to caption: extracted/5908429/figures/Transformer.png

Transformers are (pre)-trained to predict next token by minimizing the log-loss (cross-entropy loss) $\mathbb{E}_{x_{1}^{N}}[\sum_{i=1}^{N-1}\mbox{$\mathbf{x}$}_{i+1}^{\top}\log(1/
\hat{\mbox{$\mathbf{p}$}}_{i+1})]$, where $\mbox{$\mathbf{x}$}_{i}\in\mathbb{R}^{A}$ is the one-hot encoding of $x_{i}$ and sequence $x_{1}^{N}$ is sampled from some population of sources, e.g., sequences can be articles written by different authors and thus following different statistical dynamics.

### 2.2 In-context learning as Bayesian universal coding

Figure: Figure 2: ICL v.s. Bayesian Universal Coding
Refer to caption: x1.png

ICL has a natural connection to compression in information theory []. Information theory proves that a stationary data source can be compressed losslessly at a rate no less than its entropy rate []. A well-known compression algorithm is arithmetic coding [, , ], which requires an estimated *probability distribution $\hat{P}$ for the next source symbol* to compress a data source that follows the true distribution $P$. The precise compression mechanism is somewhat complicated, and theoretical guarantees vary depending on the structure of the underlying data sources. Nevertheless, it suffices for us to view it as a black box that compresses a symbol $x$ with approximately $\ln(1/\hat{P}(x))$ nats, resulting in an accumulated rate roughly equal to the cross-entropy between $\hat{P}$ and $P$; when $\hat{P}=P$, this reduces to the entropy rate. Note that the entropy rate is a lower bound for the asymptotic averaged log-loss of the transformers.

The learning aspect of ICL closely resembles universal compression []. Naïvely speaking, the latter aims to adaptively compress the source given its context, essentially approaching its entropy rate without having direct access to the underlying dynamics, but learning it in an in-context fashion. We illustrate the close analogy between ICL and Bayesian universal coding in Fig. 2, where pretraining of learning is equivalent to learning the Bayesian prior of the sources, and the next token prediction can be viewed as a part of arithmetic coding (AC), both measured by log-loss.

### 2.3 Context Tree Models (Variable-Order Markov Chains)

Figure: Figure 3: A CT in the alphabet $\mathcal{A}=\{a,b,c\}$ with suffix set $\mathcal{S}=\{(b),(c),(a,a),(b,a),(c,a)\}$ and the associated probability distributions. If $(\ldots,x_{n-1},x_{n})=(\ldots,c,a)$, then the probability distribution for the next symbol $x_{n+1}$ is $p_{c,a}$.
Refer to caption: x2.png

Variable-order Markov chains (VOMCs), also known as context tree (CT) models, have been studied extensively in the data compression literature [, , ]. String $s=(x_{1-l},x_{2-l},\ldots,x_{0})$ is a suffix of the string $s^{\prime}=(x^{\prime}_{1-l^{\prime}},x^{\prime}_{2-l^{\prime}},\ldots,x^{
\prime}_{0})$, if $0\leq l\leq l^{\prime}$ and $x_{-i}=x^{\prime}_{-i}$ for $i=0,1,\ldots,l-1$; e.g., $(a,b,c,b)$ is suffix of $(a,c,a,a,b,c,b)$. Note that the strings above have non-positive indices.

The statistical behavior of a finite memory CT source is specified by a suffix set $\mathcal{S}$ and the associated next token probability distributions. The suffix set is a collection of strings $s(k)$, $k=1,2,\ldots,|\mathcal{S}|$, which needs to be proper and complete: The set is proper if no string in $\mathcal{S}$ is a suffix of any other string; it is complete if each semi-infinite sequence $(\ldots,x_{n-1},x_{n})$ has a unique suffix that belongs to $\mathcal{S}$, denoted as $\beta_{\mathcal{S}}(\ldots,x_{n-1},x_{n})$. Associated with each suffix $s\in\mathcal{S}$, there is a probability mass function $p_{s}\in\Delta_{\mathcal{A}}$. A CT has maximum order $D$ if any suffix in $\mathcal{S}$ has
a length at most $D$. Given a semi-infinite sequence $(\ldots,x_{n-1},x_{n})$, the next symbol $x_{n+1}$ is generated randomly according to the distribution $p_{\beta_{\mathcal{S}}(\ldots,x_{n-1},x_{n})}$. An example CT is in Fig. 3. A tree structure appears since for any valid suffix set $\mathcal{S}$, there exists a unique tree $T$ with $\mathcal{S}$ being its leaves $\mathcal{L}(T)$. A CT can thus be equivalently represented by $(T,\{p_{s}\}_{s\in\mathcal{L}(T)})$.

### 2.4 Bayesian Context Tree Weighting Compression Algorithm

Once the underlying CT is estimated accurately, AC can be used to compress the sequence efficiently. The difficulty in estimating a context tree is in finding both of its components: the tree structure itself, and the probability distribution associated with each leaf node. The likelihood of a sequence $x_{1}^{i}$ given $x_{1-D}^{0}$ for a CT with parameter $(T,\{p_{s}\}_{s\in\mathcal{L}(T)})$ is

$$ $\displaystyle P_{T,\{p_{s}\}}(x_{1}^{i}|x_{1-D}^{0})=\prod_{j=1}^{i}p_{\beta_{ \mathcal{L}(T)}(x_{j-D},\ldots,x_{j-1})}(x_{j})=\prod_{s\in\mathcal{L}(T)} \prod_{a\in\mathcal{A}}p_{s}(a)^{\mbox{$\mathbf{n}$}_{i,s}(a)},$ $$

where $\mbox{$\mathbf{n}$}_{i,s}$ is the *counting vector* associated with suffix $s$ that

$$ $\displaystyle\mbox{$\mathbf{n}$}_{i,s}(a):=\text{number of times symbol }a\in \mathcal{A}\text{ follows suffix }s\text{ in sequence }(x_{1},\ldots,x_{i}).$ (5) $$

Leveraging the multiplicative nature of the likelihood function, [] proposed the
context tree weighting (CTW) algorithm for CT sources with maximum order $D$ based on the minimum description length principle. CTW estimates the probability of the sequence $x_{1}^{n}$ by the auxiliary parameters $p^{e}_{n,s},p^{w}_{n,s}$’s as follows.

- 1.
For each $s\in\mathcal{A}^{*}$ with $|s|\leq D$, compute $p^{e}_{n,s}=\frac{\Gamma(\sum_{a\in\mathcal{A}}\bm{\alpha}(a))}{\Gamma(\sum_{a
\in\mathcal{A}}(\mbox{$\mathbf{n}$}_{s}(a)+\bm{\alpha}(a))}\prod_{q\in\mathcal
{A}}\frac{\Gamma(\mbox{$\mathbf{n}$}_{s}(a)+\bm{\alpha}(a))}{\Gamma(\bm{\alpha
}(a))},$
where $\mbox{$\mathbf{n}$}_{s}$ is the counting vector $\mbox{$\mathbf{n}$}_{i,s}$ with $i=n$, $\Gamma(\cdot)$ is the Gamma function, and $\bm{\alpha}$ is a prior-related vector that will be specified later.
- 2.
From nodes in the $D$-th level to the 0 0-th level (i.e., root), iteratively compute
$\displaystyle p^{w}_{n,s}:=\left\{\begin{array}[]{ll}p^{e}_{n,s},&\;\;\mbox{if
$|s|=D$,}\\
\lambda p^{e}_{n,s}+(1-\lambda)\prod_{q\in\mathcal{A}}p^{w}_{n,qs},&\;\;\mbox{
otherwise,}\end{array}\right.$
(8)
where $qs$ is the string by appending symbol $q\in\mathcal{A}$ before the suffix $s$.

[] took the Bayesian view towards this procedure, and showed that the probability $p^{w}_{n,()}$ at the root has a clear Bayesian interpretation under a CTW prior. CTW prior $\pi_{\text{CTW}}$ is a Bayesian CT prior over the trees in $\mathcal{T}(D):=\{\text{full $A$-ary tree with depth at most $D$}\}$ and the transition distributions $p_{s}\in\Delta_{\mathcal{A}}$. Specifically, $\pi_{\text{CTW}}(T,(p_{s})_{s\in\mathcal{L}(T)})=\pi_{D}(T)\prod_{s\in\mathcal
{L}(T)}\pi_{p}(p_{s})$, where $\pi_{D}(\cdot)$ represents a bounded branching process that each node at a level lower than $D$ stops branching with probability $\lambda$ or branches to $|\mathcal{A}|$ children with probability $(1-\lambda)$; and $\pi_{p}(p_{s})$ satisfies a Dirichlet distribution. Mathematically,

$$ $\displaystyle\pi_{D}(T)$ $\displaystyle=(1-\lambda)^{(|\mathcal{L}(T)|-1)/(A-1)}\lambda^{|\mathcal{L}(T) |-|\mathcal{L}_{D}(T)|},~{}\quad\pi_{p}(p_{s})=\text{Dir}(p_{s};\{\bm{\alpha}( a)\}_{a\in\mathcal{A}}),$ $$

where $\mathcal{L}_{D}(T)$ is the leaves of $T$ with depth $D$ and $\{\bm{\alpha}(a)\}_{a\in\mathcal{A}}$ are the Dirichlet parameters. A typical choice is $\bm{\alpha}(a)=0.5$ for each $a\in\mathcal{A}$ corresponding to the Jeffreys prior.

###### Theorem 2.1 .

[, Theorem 3.1]
The $p^{w}_{n,()}$ value at root computed by the CTW procedure equals to the Bayesian predicted probability under prior $\pi_{\text{CTW}}$ specified by $(D,\lambda,\bm{\alpha})$:

$$ $\displaystyle p^{w}_{n,()}$ $\displaystyle=P_{\pi_{\text{CTW}}}(x_{1}^{n}|x_{1-D}^{0})=\sum_{T\in\mathcal{T }(D)}\int P_{T,\{p_{s}\}}(x_{1}^{n}|x_{1-D}^{0})\pi(T,\{p_{s}\}){\Big{(}}\prod _{s\in\mathcal{L}(T)}\mathrm{d}p_{s}{\Big{)}}.$ $$

This theorem implies that the CTW procedure exactly matches the Bayesian CTs with prior $\pi$ parameterized by $(D,\lambda,\bm{\alpha})$ and the probability of sequence $x_{1}^{n}$ is $p^{w}_{n,()}$, i.e., the $p^{w}$ at the root. AC can be applied via sequentially calculating the predictive next token probability as $P_{\pi_{\text{CTW}}}(x_{i+1}|x_{1-D}^{i})=\frac{P_{\pi_{\text{CTW}}}(x_{1}^{i+
1}|x_{1-D}^{0})}{P_{\pi_{\text{CTW}}}(x_{1}^{i}|x_{1-D}^{0})}$ and achieves code length at most $\lceil\log_{2}(1/p^{w}_{n,()})\rceil$ [, ].

###### Theorem 2.1 .

### 2.5 Prediction by Partial Matching

The prediction by partial matching algorithm (PPM) [] is also well known for its good performance in practice []. The PPM algorithm (with finite memory of parameter $D_{\text{PPM}}$) blends several CTs by utilizing an escape symbol (Esc), and adaptively refines the CT model using the observed samples. The key idea is that the estimated probability distribution for an emitted symbol is only used when there were past observations of this string. For other cases, the escape symbol is encoded, indicating a shorter suffix needs to be used.

**Table 1: PPM counts after observing string $(a,b,c,a,b,b,c)$**
| order $k=2$ | order $k=1$ | order $k=0$ | order $k=-1$ |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| prediction | $c$ | $p$ | prediction | $c$ | $p$ | prediction | $c$ | $p$ | prediction | $c$ | $p$ |  |  |  |  |  |  |  |  |
| $(a,b)$ | $\rightarrow$ | $b$ | $1$ | $\frac{1}{3}$ | $a$ | $\rightarrow$ | $b$ | $2$ | $\frac{2}{3}$ |  | $\rightarrow$ | $a$ | $2$ | $\frac{1}{4}$ |  |  |  |  | $\frac{1}{|\mathcal{A}|}$ |
|  | $\rightarrow$ | $c$ | $1$ | $\frac{1}{3}$ |  | $\rightarrow$ | Esc | $1$ | $\frac{1}{3}$ |  | $\rightarrow$ | $b$ | $3$ | $\frac{3}{8}$ |  |  |  |  |  |
|  | $\rightarrow$ | Esc | $1$ | $\frac{1}{3}$ | $b$ | $\rightarrow$ | $b$ | $1$ | $\frac{1}{4}$ |  | $\rightarrow$ | $c$ | $2$ | $\frac{1}{4}$ |  |  |  |  |  |
| $(b,b)$ | $\rightarrow$ | $c$ | $1$ | $\frac{1}{2}$ |  | $\rightarrow$ | $c$ | $2$ | $\frac{1}{2}$ |  | $\rightarrow$ | Esc | $1$ | $\frac{1}{8}$ |  |  |  |  |  |
|  | $\rightarrow$ | Esc | $1$ | $\frac{1}{2}$ |  | $\rightarrow$ | Esc | $1$ | $\frac{1}{4}$ |  |  |  |  |  |  |  |  |  |  |
| $(b,c)$ | $\rightarrow$ | $a$ | $1$ | $\frac{1}{2}$ | $c$ | $\rightarrow$ | $a$ | $1$ | $\frac{1}{2}$ |  |  |  |  |  |  |  |  |  |  |
|  | $\rightarrow$ | Esc | $1$ | $\frac{1}{2}$ |  | $\rightarrow$ | Esc | $1$ | $\frac{1}{2}$ |  |  |  |  |  |  |  |  |  |  |
| $(c,a)$ | $\rightarrow$ | $c$ | $1$ | $\frac{1}{2}$ |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
|  | $\rightarrow$ | Esc | $1$ | $\frac{1}{2}$ |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |

We illustrate this context tree blending approach by the example shown in Table. 1, where $\mathcal{A}=\{a,b,c\}$, and the memory length $D_{\text{PPM}}=2$. The escape pattern is assigned a count one (method-A in []). Suppose the next symbol to emit is $a$, then the probability prediction is $\frac{1}{2}$ from the $k=2$ column; if on the other hand, the next symbol to emit is $b$, then the escape symbol is first encoded with probability $\frac{1}{2}$ since there is no string of $(b,c,b)$ in the history, and then we check the column $k=1$, and see that another escape symbol will be encoded since there is also no $(c,b)$, and finally $b$ will be encoded at $k=0$, and the eventual effective probability for $b$ is $\frac{1}{2}\cdot\frac{1}{2}\cdot\frac{3}{8}$. Various refinements of the probability estimation can be adopted to further improve the performance, e.g., the exclusion rule, and other methods to initialize the probability for Esc; see e.g. [, , ]. As the number of observed samples accumulated, all patterns of $(D_{\text{PPM}}+1)$-grams will be observed at least once and the probability prediction will solely based on the column of maximum order $k=D_{\text{PPM}}$.

## 3 Transformers Learn In-context of VOMCs

Figure: Figure 4: Training data collection
Refer to caption: extracted/5908429/figures/data-collection.png

We choose ternary alphabet $|\mathcal{A}|=3$, and pretrain a transformer of context window size $N$ on data sequences of length-$N$ generated using CTs randomly sampled from a CTW prior $\pi_{\text{CTW}}$ parameterized by $\alpha=0.5$, $\lambda=0.15$ and a fixed maximum tree depth $D$, illustrated in Fig. 4.

For training, we randomly generate $K=20000$ CTs of various depths (maximum order $D\leq 5$), and then for each CT leaf, we generate a probability distribution. Two different ways of generating these probability distributions are taken: the first approach uses the Dirichlet distribution to sample such distributions, and the second approach is to randomly select some of the elements in the alphabet to have probability zero, and the others with i.i.d. random values before normalization. Different values of the Dirichlet parameter are tested but only the results do not appear to be sensitive to the choice. For each CT, a source sequence of a certain length (e.g., $N_{k}=5120$) is produced. The context window $N$ can vary, but in most cases, we set it at $512$ (except when $D=5$, we set it to be $1536$ to allow sufficient data collection in context). Each source sequence is segmented into $\lfloor N_{k}/N\rfloor$ training sequence. The training loss is the canonical next-token prediction cross-entropy loss.

During testing, we randomly generate multiple ($2048$ in our experiments) new CTs of varying depths using the same procedure, and for each CT, a sequence of length $N_{k}=5120$ is generated, and then again segmented into a length of the context window for testing.

The transformer model is implemented using Pytorch, and trained using the AdamW optimizer with the default parameters. A100/T100 GPUs are used for training. Training a model requires roughly 4 to 6 hours. Batch size is set at 512, and the maximum epoch is set at 100 with early termination allowed after 15 epochs of no improvement. Testing was performed on a local workstation with a GeForce GTX 1660 Ti GPU card.

### 3.1 Transformers Can Learn VOMC In-Context

In Fig. 6, we show the performance comparisons between trained transformers with various numbers of layers, and the reference PPM and CTW algorithms for $N=1536$ and CT maximum order $D=5$. The transformers have 8 attention heads with embedding dimension $E=128$; in our settings, we found the performance of the transformers is not constrained by these parameters. In Table 2, we further provide the average compression rates over the whole context window for CTs of different orders; we refer to the transformers as TF. For CTs with lower order, the transformer embedding dimension is set at $64$ instead of $128$.

**Table 2: Average compression rates in the context window by transformers and CTW, where the CTs are sampled from the CTW-prior. The context window and embedding dimension for CTs of $D=5$ are $N=1536$ and $E=128$, while for others it are $N=512$ and $E=64$.**
|  | TF-1 | TF-2 | TF-3 | TF-4 | TF-5 | TF-6 | CTW |
| --- | --- | --- | --- | --- | --- | --- | --- |
| CTs $D=3$ | 0.9368 | 0.7297 | 0.7265 | 0.7220 | 0.7245 | 0.7258 | 0.7165 |
| CTs $D=4$ | 0.9667 | 0.7831 | 0.7818 | 0.7759 | 0.7791 | 0.7774 | 0.7603 |
| CTs $D=5$ | 0.9661 | 0.7569 | 0.7490 | 0.7440 | 0.7437 | 0.7438 | 0.7400 |

A few observations are immediate.

1) The CTW algorithm is Bayesian optimal in this setting, and it provides a lower bound for other methods as expected.

Figure: Figure 5: Transformer, PPM, CTW
Refer to caption: x3.png

2) The PPM algorithms perform poorly in this setting, which is expected since they essentially reduce to FOMC estimators at the assumed maximum order $D_{\text{ppm}}$, for the small alphabet setting we consider. Small $D_{\text{ppm}}$ leads to oversimplification bias to the model and thus performs poorly. However, even when $D_{\text{ppm}}$ in PPM is sufficiently large, i.e., $D_{\text{ppm}}\geq D$, it is a highly inefficient estimator for those contexts at lower orders in the CT. Therefore we can view PPM as a reference method that does not adapt to the variable orders efficiently. The particular poor performance of the PPM algorithm at the start of the sequence is due to the escape symbol encoding, however, toward the end of the sequence, PPM starts to catch up better if $D_{\text{ppm}}\geq D$.

3) Most interestingly, almost all trained transformers, except that with a single layer, track the performance of the CTW algorithm fairly closely. The overall performance does improve as the number of layers increases in general; see Table 2 for numerical comparisons. Nevertheless, the improvements with increased numbers of layers are relatively small and appear to saturate at four layers. Particularly, even transformers with two layers appear to learn in context quite well.

In the next section, we provide theoretical and empirical explanations for these observations.

### 3.2 Transformers vs. CTW under Non-CTW-Priors

The CTW algorithm is known to be Bayesian optimal when the CTs are generated from a CTW-prior. When the CTs do not follow those priors, can learning-based transformers perform better than CTWs? We empirically observe that in such settings, transformers indeed have advantages. The training data are generated by using CTs of different maximum orders, where the orders are chosen uniformly at random between 1 and 3. Moreover, the probability vector is not generated from the Dirichlet prior, but from a distribution that for each CT leaf, randomly assigns one of the elements in the alphabet to have zero probability. We test on sequences generated from CTs produced from the same distribution as in the training setting. We assume the CTW takes the default (non-informative prior) parameters of $\alpha=0.5$, and the same tree branch stopping parameter $\lambda=0.15$ as taken in the testing sequence CTs.

As can be observed in Fig. 6, the CTW algorithm is no longer optimal, and trained transformers can perform considerably better. In fact, even transformers with 2 layers can outperform the CTW algorithm in this setting, and more layers usually lead to further improved performance, albeit the improvement is less significant.

## 4 Theoretical Interpretations and Empirical Evidences

To understand why and how the trained transformers perform comparable to CTW, we first analyze their attention maps, which reveal interesting patterns and behaviors. We then propose a transformer-friendly representation of the Bayesian optimal next token prediction by CTW, and motivated by the attention map observations, we provide transformer constructions to interpret its ICL capabilities and capacities. We next implement these synthetic transformer layers, and show that the hybrid transformers can match the ICL performance of the original version of transformers, which serves as evidence for the proposed constructions.

### 4.1 Analysis of Attention Maps

We analyzed the attention maps of the trained transformers where a few distinguished patterns emerge. One pattern is solely relative-position dependent. In the left two panels of Fig. 8, we observe off-diagonal stripes for these two attention heads, which are a few positions below the main diagonal. They can be a single off-diagonal or a collection of several off-diagonals. This indicates that the query position is attending positions at a few fixed but close distances ahead of itself. This pattern usually appears in the first or second layers of the transformers. Combining with the suffix structure in compression algorithms such as CTW, such an attention pattern suggests the suffix is being copied into the current query position for subsequent processing. The off-diagonal stripes may have a width greater than $1$, as shown in the second panel, which can be viewed as copying a mixture of the tokens in the suffix, suggesting the flexibility of transformers in forming certain “soft” suffixes.

Another pattern, shown in the third panel has more sophisticated spotty patterns, and the attention appears to depend more explicitly on the current token features instead of the position alone, and they usually appear in the second layer or above in the transformers. Taking query positions 350 and 362 for the attention head shown in the third panel of Fig. 7, we plot in Fig. 8 the positions in the data sequence that match their suffixes of length-$3$ using the stem plots with a black circle on top, and the attention values as the red stems with the diamonds on top. It can be seen that the positions match perfectly, though the attention weights have some variations among them. The left panel has more matching locations, due to the inherent Markov chain structure. This attention pattern suggests that it is collecting information for those positions with the matched suffix of a fixed length. Several attention heads present similar patterns but with different suffix lengths.

Figure: Figure 7: Partial attention heatmaps for different attention heads.
Refer to caption: x5.png

Figure: Figure 8: Suffix locations and attention weights in the second type of pattern at two query positions.
Refer to caption: x6.png

### 4.2 Capability and capacity of transformer via construction

Motivated by the observations of the attention map patterns, we connect the performance of transformers to CTW via construction.

#### 4.2.1 A representation of CTW optimal next token prediction

Given a sequence $x_{1}^{n}$ generated according to a CT$(T,\{p_{s}\})$ sampled from the CTW-prior $\pi_{\text{CTW}}$ parameterized by $(D,\lambda,\alpha)$, we propose a novel representation for computing the predictive probability $P_{\pi_{\text{CTW}}}(x_{n+1}|x_{1-D}^{n})$ in the following theorem, which predicts $x_{n+1}$ based on the weighted average of the next token prediction probability vector corresponding to each potential suffix $s_{n,l}:=x_{n-l+1}^{n}$ of length $l=0,1,\ldots,D$.

###### Theorem 4.1 .

The predicted probability can be computed as

$$ $\displaystyle P_{\pi_{\text{CTW}}}(x_{n+1}|x_{1}^{n})=\sum_{l=0,\ldots,D}~{} \omega_{n,l}\cdot\mbox{$\mathbf{p}$}_{n,s_{n,l}}(x_{n+1}),$ (9) $$

where $\mbox{$\mathbf{p}$}_{n,s_{n,l}}(a)=\frac{\alpha(a)+\mbox{$\mathbf{n}$}_{n,s_{n
,l}}(a)}{\sum_{q}(\alpha(q)+\mbox{$\mathbf{n}$}_{n,s_{n,l}}(q))}$; and $\omega_{n,\cdot}\in\Delta_{D+1}$ with $\ln(\omega_{n,l})-\ln(\omega_{n,l-1})=\ln(1-\lambda)-\mathbb{I}_{l=D}\ln(
\lambda)+\ell^{e}_{n,s_{n,l}}-\ell^{e}_{n,s_{n,l-1}}+\sum_{q\in\mathcal{A}}
\ell^{w}_{n,qs_{n,l-1}}-\ell^{w}_{n,s_{n,l}}$,
where $\ell^{e}_{n,s}=\ln(p^{e}_{n,s})$, $\ell^{w}_{n,s}=\ln(p^{w}_{n,s})$.

Figure: Figure 9: Illustration of Theorem 4.1
Refer to caption: x7.png

Discussion.
Note that $p^{e}_{n,s},p^{w}_{n,s}$ can be efficiently calculated by the CTW procedure, and compared to calculate $\frac{P_{\pi_{\text{CTW}}}(x_{1}^{n+1}|x_{1-D}^{0})}{P_{\pi_{\text{CTW}}}(x_{1
}^{n}|x_{1-D}^{0})}$ for each $x_{n+1}$ the extra computation besides the CTW procedure is $A$ times larger than that by Eq equation 9. As illustrated in Fig. 9, the weighted average formula in Eq equation 9 gives a natural interpretation for the Bayesian optimal next token predicted probability. Each suffix along the root the leaf path $s_{n,0}-s_{n,1}-\cdots-s_{n,D}$ can potentially be the true suffix, i.e., $s_{n,l}\in\mathcal{L}(T)$, and $\mbox{$\mathbf{p}$}_{n,s_{n,l}}$ is in fact the Bayesian optimal next token prediction given $s_{n,l}\in\mathcal{L}(T)$.

The blending weights $\omega_{n,l}$’s are based on stopping probability $\lambda$, the information in the potential suffix path such as $p^{e}_{s_{n,s_{n,l}}}$ as well as the information from their siblings $p^{w}_{n,qs_{n,l-1}}$. We can interpret $p^{e}_{n,s}$ as the evidence (unnormalized likelihood) that $s\in\mathcal{L}(T)$, and $p^{w}_{n,s}$ as the evidence that $s\in T$, i.e., the underlying tree covers node $s$. Theorem 4.1 indicates that more weights are assigned to $s_{n,l}$ than $s_{n,l-1}$, i.e., $\omega_{n,l}>\omega_{n,l-1}$, if $\lambda$ is smaller (i.e., node $s_{n,l-1}$ is more likely to branch and thus less likely to be a leaf node), $p^{e}_{n,s_{n,l}}-p^{e}_{n,s_{n,l-1}}$ is larger (i.e., $s_{n,l}$ has more evidence than $s_{n,l-1}$) and $\sum_{q\in\mathcal{A}}\ell^{w}_{n,qs_{n,l-1}}-\ell^{w}_{n,s_{n,l}}$ is larger (i.e., $s_{n,l}$’s siblings have more evidence to explain the data and thus $s_{n,l-1}$ is less likely to be a leaf node). The indicator function $\mathbb{I}_{l=D}$ is due to the maximum depth constraint on the branching process. Nodes at level $l=D$ automatically stop the branching, i.e., the branching-stopping probability is $1$ for such nodes.

###### Proof of Theorem 4.1 .

We omit $D$ by writing $\mathcal{T}=\mathcal{T}(D)$ when $D$ is clear from the context. Define partition $\{\mathcal{T}_{s_{n,l}}\}_{0\leq l\leq D}$, that $\mathcal{T}_{s}=\{T\in\mathcal{T}:s\in\mathcal{L}(T)\}$ is the set of trees containing leaf $s$. The predicted probability can then be computed as

$$ $\displaystyle P_{\pi_{\text{CTW}}}(x_{n+1}|x_{1-D}^{n})$ $\displaystyle=\sum_{T\in\mathcal{T}}\int p(x_{n+1}|T,\{p_{s}\},x_{1-D}^{n})\pi _{\text{CTW}}(T,\{p_{s}\}|x_{1-D}^{n}){\Big{(}}\prod_{s\in\mathcal{L}(T)} \mathrm{d}p_{s}{\Big{)}}$ $\displaystyle=\sum_{l=0,\ldots,D}~{}\sum_{T\in\mathcal{T}_{s_{n,l}}}\int p_{s_ {n,l}}(x_{n+1})\pi_{\text{CTW}}(T,\{p_{s}\}|x_{1-D}^{n}){\Big{(}}\prod_{s\in \mathcal{L}(T)}\mathrm{d}p_{s}{\Big{)}}$ $\displaystyle=\sum_{l=0,\ldots,D}~{}\sum_{T\in\mathcal{T}_{s_{n,l}}}\int p_{s_ {n,l}}(x_{n+1})\pi_{D}(T|x_{1-D}^{n})\pi_{p}(p_{s_{l}}|T,x_{1-D}^{n})\mathrm{d }p_{s_{l}}$ $\displaystyle=\sum_{l=0,\ldots,D}~{}\sum_{T\in\mathcal{T}_{s_{n,l}}}\pi_{D}(T| x_{1-D}^{n})\int p_{s_{n,l}}(x_{n+1})\pi_{p}(p_{s_{l}}|T,x_{1-D}^{n})\mathrm{d }p_{s_{l}}$ $\displaystyle=\sum_{l=0,\ldots,D}~{}{\Big{(}}\sum_{T\in\mathcal{T}_{s_{n,l}}} \pi_{D}(T|x_{1-D}^{n}){\Big{)}}\left(\int p_{s_{n,l}}(x_{n+1})\pi_{p}(p_{s_{l} }|T,x_{1-D}^{n})\mathrm{d}p_{s_{l}}\right)$ $\displaystyle=\sum_{l=0,\ldots,D}~{}\omega_{n,l}\cdot\mbox{$\mathbf{p}$}_{n,s_ {n,l}}(x_{n+1}),$ (10) $$

where the last equality is by the definition that

$$ $\displaystyle\omega_{n,l}=\sum_{T\in\mathcal{T}_{s_{n,l}}}\pi_{D}(T|x_{1-D}^{n }),$ (11) $$

and the optimal prediction probability given suffix $s_{n,l}$ is

$$ $\displaystyle\mbox{$\mathbf{p}$}_{n,s_{n,l}}(a)=\frac{\bm{\alpha}(a)+\mbox{$ \mathbf{n}$}_{n,s_{n,l}}(a)}{\sum_{q\in\mathcal{A}}(\bm{\alpha}(q)+\mbox{$ \mathbf{n}$}_{n,s_{n,l}}(q))},$ (12) $$

since for any $T\in\mathcal{T}_{s_{l}}$, the posterior of $p_{s}$ follows Dirichlet distribution

$$ $\displaystyle\pi_{p}(p_{s_{l}}|T,x_{1-D}^{n})=\text{Dir}(p_{s_{l}};\bm{\alpha} +\mbox{$\mathbf{n}$}_{n,s_{n,l}}),$ (13) $$

with posterior mean $\mathbb{E}[p_{s_{l}}|T,x_{1-D}^{n}]\in\Delta_{\mathcal{A}}$ and proportional to $\bm{\alpha}+\mbox{$\mathbf{n}$}_{n,s_{n,l}}$.

Since the length of data $n$ is fixed and clear from the context, let $\underline{x}=x_{1-D}^{n}$ be the sequence, and we omit $n$ in the subscript of $p^{e}_{n,s}$, $p^{w}_{n,s}$ and $s_{n,l}$ for simplicity.

For any model $T\in\mathcal{T}(D)$, the posterior probability $\pi(T|\underline{x})$ is given by:

$$ $\pi_{D}(T|\underline{x})=\frac{\pi_{D}(T)P_{\pi}(\underline{x}|T)}{P_{\pi}( \underline{x})}=\frac{\pi_{D}(T)\prod_{s\in\mathcal{L}(T)}p^{e}_{s}}{p^{w}_{() }},$ (14) $$

where the denominator $P_{\pi}^{*}(\underline{x})=p^{w}_{()}$ is the prior predictive likelihood computed by CTW given in Theorem 2.1, and the numerator is by $P_{\pi}(\underline{x}|T)=\prod_{s\in\mathcal{L}(T)}p^{e}_{s}$ in [, Lemma 2.2].
Since $\omega_{l}=\sum_{T\in\mathcal{T}_{s_{l}}}\pi(T|\underline{x})$ by definition, we have for any $l=1,2,\ldots,d$,

$$ $\displaystyle\frac{\omega_{l}}{\omega_{l-1}}=\frac{\sum_{T^{\prime}\in\mathcal {T}_{s_{l}}}\pi_{d}(T^{\prime}|x)}{\sum_{T\in\mathcal{T}_{s_{l-1}}}\pi_{d}(T|x )}=\frac{\sum_{T^{\prime}\in\mathcal{T}_{s_{l}}}\pi_{d}(T^{\prime})\prod_{s\in \mathcal{L}(T^{\prime})}p^{e}_{s}}{\sum_{T\in\mathcal{T}_{s_{l-1}}}\pi_{d}(T) \prod_{s\in\mathcal{L}(T)}p^{e}_{s}}.$ (15) $$

Note that tree in $\mathcal{T}_{s_{l}}$ and trees in $\mathcal{T}_{s_{l-1}}$ share similarities. For any $T\in\mathcal{T}_{s_{l-1}}$, let $\mathcal{T}_{s_{l};T}=\{T^{\prime}\in\mathcal{T}_{s_{l}}:\mathcal{L}(T)\subset
\mathcal{L}(T^{\prime})\cup\{s_{l-1}\}\}$ be the set of trees that differs from $T$ only at subtree $\text{sub}(T^{\prime};s_{l}):=\{\text{subtree of $T^{\prime}$ with root at $s$}\}$.

Take any $l=1,2,\ldots,D-1$. For any $T\in\mathcal{T}_{s_{l-1}}$ and $T^{\prime}\in\mathcal{T}_{s_{l};T}$. Based on the definition of $\pi_{D}=(1-\lambda)^{(|\mathcal{L}(T)|-1)/(A-1)}\lambda^{|\mathcal{L}(T)|-|
\mathcal{L}_{D}(T)|}$, it is not hard to verify that

$$ $\displaystyle\frac{\pi_{D}(T^{\prime})}{\pi_{D}(T)}$ $\displaystyle=\frac{\pi_{D-l+1}(\text{sub}(T^{\prime};s_{l-1}))}{\pi_{D-l+1}( \text{sub}(T;s_{l-1}))}$ $\displaystyle=\frac{(1-\lambda)\pi_{D-l}(\text{sub}(T^{\prime};s_{l}))\prod_{s ^{\prime}_{l}\in\text{sib}(s_{l})}\pi_{D-l}(\text{sub}(T^{\prime};s_{l}^{ \prime}))}{\lambda}$ $\displaystyle=(1-\lambda)\prod_{s^{\prime}_{l}\in\text{sib}(s_{l})}\pi_{D-l}( \text{sub}(T^{\prime};s_{l}^{\prime})),$ $$

where $\text{sib}(s_{l+1})=\{qs_{l}:q\in\mathcal{A}\text{ and }qs_{l}\not=s_{l+1}\}$ is set of siblings of $s_{l+1}$. We can interpret the ratio as follows. $T^{\prime}$ and $T$ only differs at the $\text{sub}(T^{\prime};s_{l-1})$ and $\text{sub}(T;s_{l-1})$. Since $T^{\prime}$ branch at node $s_{l-1}$, we thus have the numerator in the second equation, where $(1-\lambda)$ corresponds to the branching and then compute for the subtrees. Note that $T$ stops branching at $s_{l-1}$ and $T^{\prime}$ stops branching at $s_{l}$, then $\pi_{D-l+1}(\text{sub}(T;s_{l-1}))=\pi_{D-l}(\text{sub}(T^{\prime};s_{l}))=\lambda$ equals to the stopping probability.

Given any suffix $s$ with $|s|\leq D$, it has been shown in [, Proof of Theorem 3.1] that for any $l\leq D$,

$$ $\displaystyle p^{w}_{s}=\sum_{U\in\mathcal{T}(D-l)}\pi_{D-l}(U)\prod_{u\in \mathcal{L}(U)}p^{e}_{us},$ (16) $$

where $\mathcal{T}(D-l)$ is the set of trees with maximum depth $D-l$ and $\pi_{D-l}$ is the prior for bounded branching process with maximum depth $D-l$. We thus have

$$ $\displaystyle\frac{\sum_{T^{\prime}\in\mathcal{T}_{s_{l};T}}\pi_{D}(T^{\prime} )\prod_{s\in\mathcal{L}(T^{\prime})}p^{e}_{s}}{\pi_{D}(T)\prod_{s\in\mathcal{L }(T)}p^{e}_{s}}=\frac{\sum_{T^{\prime}\in\mathcal{T}_{s_{l};T}}\pi_{D}(T^{ \prime})\prod_{s\in\mathcal{L}(T^{\prime})}p^{e}_{s}}{\pi_{D}(T)\prod_{s\in \mathcal{L}(T)}p^{e}_{s}}$ (17) $\displaystyle=\sum_{T^{\prime}\in\mathcal{T}_{s_{l};T}}\frac{\pi_{D}(T^{\prime })}{\pi_{D}(T)}\frac{\prod_{s\in\mathcal{L}(T^{\prime})\setminus\mathcal{L}(T) }p^{e}_{s}}{p^{e}_{s_{l-1}}}$ (18) $\displaystyle=\sum_{T^{\prime}\in\mathcal{T}_{s_{l};T}}\left((1-\lambda)\prod_ {s^{\prime}_{l}\in\text{sib}(s_{l})}\pi_{D-l}(\text{sub}(T^{\prime};s_{l}^{ \prime}))\right)\left(\frac{p^{e}_{s_{l}}\prod_{s^{\prime}_{l}\in\text{sib}(T; s_{l})}\prod_{s\in\mathcal{L}(\text{sub}(T^{\prime};s^{\prime}_{l}))}p^{e}_{s} }{p^{e}_{s_{l-1}}}\right)$ (19) $\displaystyle=(1-\lambda)\frac{p^{e}_{s_{l}}}{p^{e}_{s_{l-1}}}\sum_{T^{\prime} \in\mathcal{T}_{s_{l};T}}\left(\prod_{s^{\prime}_{l}\in\text{sib}(s_{l})}\pi_{ D-l}(\text{sub}(T^{\prime};s_{l}^{\prime}))\right)\left(\prod_{s^{\prime}_{l} \in\text{sib}(T;s_{l})}\prod_{s\in\mathcal{L}(\text{sub}(T^{\prime};s^{\prime} _{l}))}p^{e}_{s}\right)$ (20) $\displaystyle=(1-\lambda)\frac{p^{e}_{s_{l}}}{p^{e}_{s_{l-1}}}\sum_{T^{\prime} \in\mathcal{T}_{s_{l};T}}\left(\prod_{s^{\prime}_{l}\in\text{sib}(s_{l})}\pi_{ D-l}(\text{sub}(T^{\prime};s_{l}^{\prime}))\prod_{s\in\mathcal{L}(\text{sub}(T ^{\prime};s^{\prime}_{l}))}p^{e}_{s}\right)$ (21) $\displaystyle=(1-\lambda)\frac{p^{e}_{s_{l}}}{p^{e}_{s_{l-1}}}\prod_{s^{\prime }_{l}\in\text{sib}(s_{l})}\left(\sum_{U\in\mathcal{T}(D-l)}\pi_{D-l}(U)\prod_{ u\in\mathcal{L}(U)}p^{e}_{us^{\prime}_{l}}\right)$ (22) $\displaystyle=\frac{(1-\lambda)p^{e}_{s_{l}}\prod_{a\not=s_{l}\setminus s_{l-1 }}p^{w}_{as_{l-1}}}{p^{e}_{s_{l-1}}}.$ (23) $$

Similarly, for any $T\in\mathcal{T}_{s_{D-1}}$ and $T^{\prime}\in\mathcal{T}_{s_{D};T}$, $\frac{\pi_{D}(T^{\prime})}{\pi_{D}(T)}=\frac{1-\lambda}{\lambda}$, we can derive

$$ $\displaystyle\frac{\omega_{D}}{\omega_{D-1}}=\frac{(1-\lambda)p^{e}_{s_{d}} \prod_{a\not=s_{d}\setminus s_{i}}p^{w}_{as_{D-1}}}{\lambda p^{e}_{s_{D-1}}},$ (24) $$

in the same manner. The proof can then be concluded by taking the logarithm on both hands.
∎

###### Theorem 4.1 .

###### Proof of Theorem 4.1 .

#### 4.2.2 Transformer construction: Approximating CTW

We provide a construction of $(2+D)$-layer transformer with sufficient representation power in the FF layer that can essentially approximate CTW, demonstrating transformers’ capacity. The first two layers are motivated by the attention map patterns observed in Section 4.1, which we show their capabilities of capturing the important counting vector statistics suggested by Theorem 4.1. The last $D$ layers are induction layers imitating the CTW procedure.

We consider the initial embedding to be one-hot, with additional scratch pad elements initialized as zeros and a positional embedding, i.e., the $i$-th column of $\mbox{$\mathbf{H}$}^{(1)}$ is

$$ $\displaystyle\mbox{$\mathbf{h}$}^{(1)}_{i}=(\mbox{$\mathbf{x}$}_{i};\mbox{$ \mathbf{0}$};\mbox{$\mathbf{pos}$}_{i})\in\mathbb{R}^{E},$ (25) $$

where we used $\mbox{$\mathbf{x}$}_{i}\in\mathbb{R}^{A}$ to denote the one-hot (column vector) embedding of $x_{i}$ and a sinusoidal positional embedding $\mbox{$\mathbf{pos}$}_{i}=(1;\cos(i\pi/N);\sin(i\pi/N))$, with $N$ being the maximum context window size, and the remaining $(E-A-3)$ elements being zero. The parameter $E$ will be specified later, and let us assume it is sufficiently large at this point. For simplicity of presentation, we take $E^{(\ell)}=E$ and $W_{O}^{(\ell)}=[\mbox{$\mathbf{I}$};\mbox{$\mathbf{I}$};\ldots;\mbox{$\mathbf{
I}$}]$. It is not hard to see the following constructions can be applied to much smaller $E^{(\ell)}$ while taking $W_{O}$ as a permutation matrix. We have omitted the dimensionality of several zero matrices when they are obvious from the context.

To make the presentation clear, in the following we separate the layers by their functionality and present them separately. We begin with the first layer, which is referred to as a finite-memory context-extension layer.

###### Theorem 4.2 .

There is an $M$-headed transformer layer that can perform finite-memory context extension, defined by the following output, with the initial one-hot embedded input $\mbox{$\mathbf{H}$}^{(1)}$:

$$ $\displaystyle\mbox{$\mathbf{h}$}^{(2)}_{i}=(\mbox{$\mathbf{s}$}_{i,M+1};\mbox{ $\mathbf{0}$};\mbox{$\mathbf{pos}$}_{i}),$ (26) $$

where $\mbox{$\mathbf{s}$}_{i,M+1}=(\mbox{$\mathbf{x}$}_{i};\ldots;\mbox{$\mathbf{x}$
}_{i-M})$ is the vector version of the $M$-length suffix $s_{i,M+1}=x_{i-M}^{i}$.

This layer essentially copies $M$ past embedded symbols to the current position $i$, and stacks them below the current symbol $\mbox{$\mathbf{x}$}_{i}$. This operation utilizes the positional encoding $\mbox{$\mathbf{pos}$}_{i}$ via rotation and matching the corresponding positions.

###### Proof of Theorem 4.2 .

The multi-head attention in the first layer is consisted of $M^{(1)}=M$ heads parameterized by $(W^{(1)}_{Q,m},W^{(1)}_{K,m},W^{(1)}_{V,m})_{m=1,2,\ldots,M^{(1)}}$. Specifically, for $m=1,2,\ldots,M^{(1)}$,

$$ $\displaystyle W_{Q,m}^{(1)}=\begin{pmatrix}\mbox{$\mathbf{0}$}&\text{Rot}(m)\\ \mbox{$\mathbf{0}$}&\mbox{$\mathbf{0}$}\end{pmatrix},\quad W_{K,m}^{(1)}= \begin{pmatrix}\mbox{$\mathbf{0}$}&c\mbox{$\mathbf{I}$}^{2\times 2}\\ \mbox{$\mathbf{0}$}&\mbox{$\mathbf{0}$}\end{pmatrix},\quad W_{V,m}^{(1)}= \begin{pmatrix}\mbox{$\mathbf{0}$}^{mA\times A}&\mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{I}$}^{A\times A}&\mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{0}$}&\mbox{$\mathbf{0}$}\end{pmatrix},$ (27) $$

where $\text{Rot}(m)=\begin{pmatrix}\cos(m\pi/N)&\sin(m\pi/N)\\
-\sin(m\pi/N)&\cos(m\pi/N)\end{pmatrix}$ is a rotation matrix that rotates clockwise by an angle of $m\pi/C$, and $c\in\mathbb{R}_{+}$ is a temperature factor. The query, key, and value after the mapping are

$$ $\displaystyle W^{(1)}_{Q,m}\mbox{$\mathbf{h}$}_{n}^{(1)}=\begin{pmatrix}\mbox{ $\mathbf{pos}$}_{n-m}\\ \mbox{$\mathbf{0}$}\end{pmatrix},\quad W^{(1)}_{K,m}\mbox{$\mathbf{h}$}_{i}^{( 1)}=c\begin{pmatrix}\mbox{$\mathbf{pos}$}_{i}\\ \mbox{$\mathbf{0}$}\end{pmatrix},\quad W^{(1)}_{V,m}\mbox{$\mathbf{h}$}_{i}^{( 1)}=\begin{pmatrix}\mbox{$\mathbf{0}$}^{mA\times 1}\\ \mbox{$\mathbf{x}$}_{i}\\ \mbox{$\mathbf{0}$}\end{pmatrix}.$ (28) $$

Take $c=\infty$ or sufficiently large. It is seen that the $m$-th head essentially copies the $m$-th earlier symbol to stack at the $(m+1)$-th position below the original symbol $\mbox{$\mathbf{x}$}_{i}$. Together with the residual link, we conclude the theorem by setting the FF layer in this layer as all zeros. ∎

The second layer is referred to as the statistics collection layer, which takes a sequence of vectors $\mbox{$\mathbf{h}$}^{(2)}_{i}$, $i=1,\ldots,N$, defined in (26) as its input. To rigorously specify the function of this layer, we define the $k$-gram (forward) statistics vector $\mbox{$\mathbf{g}$}_{i,s}$ with $|s|=k-1$, which in plain words, is the empirical probability distribution of the next token associated with the suffix $s$ for a sequence $x_{1}^{i}$. Similarly, we define the $k$-gram backward statistics vector $\mbox{$\mathbf{g}$}_{i-1,s}^{\leftarrow}$, which is the empirical probability distribution of the previous token associated with the suffix $s$ for $x_{1}^{i-1}$. Mathematically, for a suffix $s$ and position $i$,

$$ $\displaystyle\mbox{$\mathbf{g}$}_{i,s}(a)=\frac{\mbox{$\mathbf{n}$}_{i,s}(a)}{ \sum_{q\in\mathcal{A}}\mbox{$\mathbf{n}$}_{i,s}(q)},\qquad\mbox{$\mathbf{g}$}_ {i-1,s}^{\leftarrow}(a)=\frac{\sum_{q\in\mathcal{A}}\mbox{$\mathbf{n}$}_{i,as} (q)}{\sum_{q\in\mathcal{A}}\mbox{$\mathbf{n}$}_{i,s}(q)},\qquad\forall a\in \mathcal{A},$ (29) $$

where $\mbox{$\mathbf{n}$}_{i,s}$ is the counting vector defined in (5), and $\sum_{q\in\mathcal{A}}\mbox{$\mathbf{n}$}_{i,s}(q)$ is the number of appears of the string $s$ in the sequence $x_{1}^{i-1}$. For both $\mbox{$\mathbf{g}$}_{i,s}$ and $\mbox{$\mathbf{g}$}_{i-1,s}^{\leftarrow}$, if the suffix $s$ has not appeared in data $x_{1}^{i-1}$, it can be initialized arbitrarily as a vector in the probability simplex.

###### Theorem 4.3 .

There is an $M^{\prime}$-head attention layer, where $M^{\prime}\leq M+1$, that can perform statistics collection, defined by the following output, with $\mbox{$\mathbf{H}$}^{(2)}$ in (26) as its input:

$$ $\displaystyle\mbox{$\mathbf{a}$}^{(2)}_{i}=(\mbox{$\mathbf{s}$}_{i,M+1};\mbox{ $\mathbf{g}$}_{i,M^{\prime}};\mbox{$\mathbf{g}$}^{\leftarrow}_{i-1,M^{\prime}} ;\mbox{$\mathbf{0}$};\mbox{$\mathbf{pos}$}_{i}),$ (30) $$

where $\mbox{$\mathbf{g}$}_{i,M^{\prime}}:=(\mbox{$\mathbf{g}$}_{i,s_{i,0}};\ldots;
\mbox{$\mathbf{g}$}_{i,s_{i,M^{\prime}-1}})$ and $\mbox{$\mathbf{g}$}^{\leftarrow}_{i-1,M^{\prime}}=(\mbox{$\mathbf{g}$}^{
\leftarrow}_{i-1,s_{i,0}};\ldots;\mbox{$\mathbf{g}$}^{\leftarrow}_{i-1,s_{i,M^
{\prime}-1}})$.

This functional layer essentially collects $k$-gram statistics for various lengths of $k=1,2,\ldots,M^{\prime}$. For example, when $k=3$, it collects the normalized frequency associated with the suffix $(x_{n-1},x_{n})$. The first and second layer constructions are illustrated in Fig. 10.

###### Proof of Theorem 4.3 .

The multi-head attention in the second layer is consisted of $M^{(2)}=M^{\prime}\leq M^{(1)}+1=M+1$ heads parameterized by $(W^{(2)}_{Q,m},W^{(2)}_{K,m},W^{(2)}_{V,m})_{m=0,1,2,\ldots,M^{(2)}-1}$. Specifically, for $m=1,2,\ldots,M^{(2)}-1$,

$$ $\displaystyle W_{Q,m}^{(2)}$ $\displaystyle=\begin{pmatrix}\mbox{$\mathbf{I}$}^{(m-1)A\times(m-1)A}&\mbox{$ \mathbf{0}$}\\ \mbox{$\mathbf{0}$}&\mbox{$\mathbf{0}$}\end{pmatrix},~{}W_{K,m}^{(2)}=\begin{ pmatrix}\mbox{$\mathbf{0}$}^{(m-1)A\times A}&c\mbox{$\mathbf{I}$}^{(m-1)A \times(m-1)A}&\mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{0}$}&\mbox{$\mathbf{0}$}&\mbox{$\mathbf{0}$}\end{pmatrix},$ $\displaystyle~{}W_{V,m}^{(2)}$ $\displaystyle=\begin{pmatrix}\mbox{$\mathbf{0}$}^{(M^{(1)}+m)A\times A}&\mbox{ $\mathbf{0}$}\\ \mbox{$\mathbf{I}$}^{A\times A}&\mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{0}$}^{(M^{(2)}-1)A\times A}&\mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{0}$}^{A\times A}&[\mbox{$\mathbf{0}$}^{A\times(m-1)A},\mbox{$ \mathbf{I}$}^{A\times A},\mbox{$\mathbf{0}$}]\\ \mbox{$\mathbf{0}$}&\mbox{$\mathbf{0}$}\end{pmatrix}.$ $$

The corresponding query, key, and value vectors after the mapping are

$$ $\displaystyle W^{(2)}_{Q,m}\mbox{$\mathbf{h}$}_{n}^{(2)}$ $\displaystyle=\begin{pmatrix}\mbox{$\mathbf{s}$}_{n,m-1}\\ \mbox{$\mathbf{0}$}\end{pmatrix},\quad W^{(2)}_{K,m}\mbox{$\mathbf{h}$}_{i}^{( 2)}=c\begin{pmatrix}\mbox{$\mathbf{s}$}_{i-1,m-1}\\ \mbox{$\mathbf{0}$}\end{pmatrix},\quad W^{(2)}_{V,m}\mbox{$\mathbf{h}$}_{i}^{( 2)}$ $\displaystyle=\begin{pmatrix}\mbox{$\mathbf{0}$}^{(M^{(1)}+m)A\times 1}\\ \mbox{$\mathbf{x}$}_{i}\\ \mbox{$\mathbf{0}$}^{(M^{(2)}-1)A\times 1}\\ \mbox{$\mathbf{x}$}_{i-m}\\ \mbox{$\mathbf{0}$}\end{pmatrix}.$ $$

For $m=M^{(2)}$, $W_{Q,m}^{(2)},W_{K,m}^{(2)}$ are of the same structure, while $W^{(2)}_{V,m}$ does not contains that $\mbox{$\mathbf{I}$}^{A\times A}$ in that $[\mbox{$\mathbf{0}$}^{A\times(m-1)A},\mbox{$\mathbf{I}$}^{A\times A},\mbox{$
\mathbf{0}$}]$ block, and thus $W^{(1)}_{V,m}\mbox{$\mathbf{h}$}_{i}^{(1)}$ does not have $\mbox{$\mathbf{x}$}_{i-m}$. It is not hard to see that taking $c\rightarrow\infty$ gives

$$ $\displaystyle(\mbox{$\mathbf{s}$}_{i,M^{(1)}+1};\mbox{$\mathbf{g}$}_{i,M^{(2)} -1};\mbox{$\mathbf{g}$}^{\leftarrow}_{i-1,M^{(2)}-1};\mbox{$\mathbf{0}$};\mbox {$\mathbf{pos}$}_{i})=\mbox{$\mathbf{a}$}^{(2)}_{i}=[\text{MHA}(\mbox{$\mathbf {H}$}^{(2)})+\mbox{$\mathbf{H}$}^{(2)}]_{i}.$ (31) $$

∎

For ICL of FOMCs, two-layer transformers collecting forward statistics $\mbox{$\mathbf{g}$}_{i,M^{\prime}}$ with $M^{\prime}=D+1$ is sufficient []. However, for the ICL-VOMC task, the underlying CT structure is unknown, therefore, collecting such simple statistics is no longer sufficient. As indicated in Theorem 4.1, the information of counting statistics $\mbox{$\mathbf{n}$}_{i,s_{i,l}}$ is important to the performance of prediction since the weights heavily depend on $\mbox{$\mathbf{n}$}_{i,s}(a)$. Yet due to the softmax function of the attention layer, only (normalized) probabilistic vector can be obtained instead of the exact count. With the backward statistics $\mbox{$\mathbf{g}$}^{\leftarrow}_{i,s}$, $\mbox{$\mathbf{n}$}_{i,s_{i,l}}$ can be derived as

$$ $\displaystyle\mbox{$\mathbf{n}$}_{i,s_{i,l}}(a)$ $\displaystyle=\frac{\mbox{$\mathbf{n}$}_{i,s_{i,l}}(a)}{\sum_{q\in\mathcal{A}} \mbox{$\mathbf{n}$}_{i,s_{i,l}}(q)}\frac{\sum_{q\in\mathcal{A}}\mbox{$\mathbf{ n}$}_{i,s_{i,l}}(q)}{\sum_{q\in\mathcal{A}}\mbox{$\mathbf{n}$}_{i,s_{i,l-1}}(q )}\cdots\frac{\sum_{q\in\mathcal{A}}\mbox{$\mathbf{n}$}_{i,s_{i,1}}(q)}{\sum_{ q\in\mathcal{A}}\mbox{$\mathbf{n}$}_{i,s_{i,0}}(q)}\left(\sum_{q\in\mathcal{A} }\mbox{$\mathbf{n}$}_{i,s_{i,0}}(q)\right)$ $\displaystyle=\mbox{$\mathbf{g}$}_{i,s_{i,l}}(a)\left(\prod_{j=0}^{l-1}\mbox{$ \mathbf{g}$}_{i-1,s_{i,j}}^{\leftarrow}(x_{i-j})\right)\cdot i,$ $$

by the information contained in vector $\mbox{$\mathbf{a}$}_{i}^{(2)}$.

Figure: Figure 10: Transformer construction for $D=2$. The left figure illustrates the first layer – finite-memory context-extension layer, which appends the previous $D$ tokens. The right figure demonstrates the MHA of the second layer – statistics collection layer, which extracts forward and backward statistics based on the matched suffix indicated by a green square.
Refer to caption: extracted/5908429/figures/first-layer.png

Taking $M=M^{\prime}-1=D$, after the statistics collection multi-head attention layer, a sufficiently wide FF layer can give

$$ $\displaystyle\mbox{$\mathbf{h}$}^{(3)}_{i}=(\mbox{$\mathbf{s}$}_{i,D};\mbox{$ \mathbf{p}$}_{i,D};\mbox{$\mathbf{l}$}^{e}_{i,D};\ell^{w}_{i,s_{i,D}};\mbox{$ \mathbf{0}$};\mbox{$\mathbf{pos}$}_{i}),$ (32) $$

where $\mbox{$\mathbf{p}$}_{i,D}=(\mbox{$\mathbf{p}$}_{i,s_{i,0}};\mbox{$\mathbf{p}$}
_{i,s_{i,1}};\ldots;\mbox{$\mathbf{p}$}_{i,s_{i,D}})$ and $\mbox{$\mathbf{l}$}^{e}_{i,D}=(\ell^{e}_{i,s_{i,0}};\ldots;\ell^{e}_{i,s_{i,D}})$.

To fulfill the Bayesian optimal prediction, we introduce the following induction layer that iteratively computes $\ell^{w}_{i,s}$ for suffix on the valid suffix path and their siblings, and also the weight difference denoted by $\delta_{i,l}:=\ln(\omega_{i,l})-\ln(\omega_{i,l-1})$ for $l=d,D-1,\ldots,1$. Specifically, the desired embedding

$$ $\displaystyle\mbox{$\mathbf{h}$}^{(\ell)}_{i}=(\mbox{$\mathbf{s}$}_{i,M^{(1)}+ 1};\mbox{$\mathbf{p}$}_{i,D};\mbox{$\mathbf{l}$}^{e}_{i,D};\delta_{i,D};\delta _{i,D-1};\ldots;\delta_{i,D-\ell+4};\ell^{w}_{i,s_{i,D+3-\ell}};\mbox{$\mathbf {0}$};\mbox{$\mathbf{pos}$}_{i}),$ (33) $$

for $\ell=3,4,\ldots,3+D$.

###### Theorem 4.4 .

There exists a $A$-head transformer layer that can perform the induction: Takes $\mbox{$\mathbf{H}$}^{(\ell)}$ in (33) as input and outputs $\mbox{$\mathbf{H}$}^{(\ell+1)}$. And the final output layer taking $\mbox{$\mathbf{H}$}^{(D+3)}$ as input can output the $A$-dimensional Bayesian optimal next token prediction vector
$P_{\pi_{\text{CTW}}}(\cdot|x_{1-D}^{n})=\sum_{l=0,\ldots,D}~{}\omega_{n,l}
\mbox{$\mathbf{p}$}_{n,s_{n,l}}.$

###### Proof of Theorem 4.4 .

For any fixed $\ell=3,4,\ldots,2+D$, we specify the construction for the $\ell$-th transformer layer. It contains $A$ heads and for each $m=1,2,\ldots,A$, the $Q,K,V$ matrices are

$$ $\displaystyle W_{Q,m}^{(\ell)}$ $\displaystyle=\begin{pmatrix}\mbox{$\mathbf{I}$}^{(D+1-\ell)A\times(D+1-\ell)A }&\mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{0}$}&[\mbox{$\mathbf{e}$}_{m},\mbox{$\mathbf{0}$}^{A\times 2}] \\ \mbox{$\mathbf{0}$}&\mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{0}$}&\mbox{$\mathbf{I}$}^{2\times 2}\end{pmatrix},~{}W_{K,m}^{( \ell)}=\begin{pmatrix}c\mbox{$\mathbf{I}$}^{(D+2-\ell)A\times(D+2-\ell)A}& \mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{0}$}&\mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{0}$}&c\mbox{$\mathbf{I}$}^{2\times 2}\end{pmatrix},$ $\displaystyle W_{V,m}^{(\ell)}$ $\displaystyle=\begin{pmatrix}\mbox{$\mathbf{0}$}^{(\text{place}_{\ell}+m) \times(\text{place}_{\ell}+m)}&\mbox{$\mathbf{0}$}\\ [\mbox{$\mathbf{0}$}^{1\times(\text{place}_{\ell}-1)},1]&\mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{0}$}&\mbox{$\mathbf{0}$}\end{pmatrix},$ $$

where $\mbox{$\mathbf{e}$}_{m}$ is the $A$-dimensional one-hot vector at position $m$, and $\text{place}_{\ell}=(M^{(1)}+D+2)A+D+\ell-1$ is index of element $\ell^{w}_{i,s_{i,D+3-\ell}}$ in $\mbox{$\mathbf{h}$}_{i}^{(\ell)}$.
The corresponding query, key, and value vectors after the mapping are

$$ $\displaystyle W^{(\ell)}_{Q,m}\mbox{$\mathbf{h}$}_{n}^{(\ell)}$ $\displaystyle=\begin{pmatrix}\mbox{$\mathbf{s}$}_{n,D+1-\ell}\\ \mbox{$\mathbf{e}$}_{m}\\ \mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{pos}$}_{n}\end{pmatrix},\quad W^{(\ell)}_{K,m}\mbox{$\mathbf{h} $}_{i}^{(\ell)}=c\begin{pmatrix}\mbox{$\mathbf{s}$}_{i,D+2-\ell}\\ \mbox{$\mathbf{0}$}\\ \mbox{$\mathbf{pos}$}_{i}\end{pmatrix},\quad W^{(\ell)}_{V,m}\mbox{$\mathbf{h} $}_{i}^{(\ell)}$ $\displaystyle=\begin{pmatrix}\mbox{$\mathbf{0}$}^{(\text{place}_{\ell}+m) \times 1}\\ \ell^{w}_{i,s_{i,D+3-\ell}}\\ \mbox{$\mathbf{0}$}\end{pmatrix}.$ $$

At position $n$, the query of $m$-head will select the latest (due to positional embedding) position with suffix $[\mbox{$\mathbf{s}$}_{n,D+1-\ell};\mbox{$\mathbf{e}$}_{m}]$, and append its $\ell^{w}$ at the end. It is not hard to see that taking $c\rightarrow\infty$ gives

$$ $\displaystyle\mbox{$\mathbf{a}$}_{i}^{(\ell)}=[\text{MHA}(\mbox{$\mathbf{H}$}^ {(2)})+\mbox{$\mathbf{H}$}^{(2)}]_{i}$ $\displaystyle=(\mbox{$\mathbf{s}$}_{i,D+1};\mbox{$\mathbf{p}$}_{i,D};\mbox{$ \mathbf{l}$}^{e}_{i,D};\delta_{i,D};\delta_{i,D-1};\ldots;\delta_{i,D+4-\ell}; \ell^{w}_{i,s_{i,D+3-\ell}};[\ell^{w}_{i,qs_{i,D+2-\ell}}]_{q\in\mathcal{A}}; \mbox{$\mathbf{0}$};\mbox{$\mathbf{pos}$}_{i})$ $$

Recall $\ln(\omega_{n,l})-\ln(\omega_{n,l-1})=\ln(1-\lambda)-\mathbb{I}_{l=D}\ln(
\lambda)+\ell^{e}_{n,s_{n,l}}-\ell^{e}_{n,s_{n,l-1}}+\sum_{q\in\mathcal{A}}
\ell^{w}_{n,qs_{n,l-1}}-\ell^{w}_{n,s_{n,l}}$ by Theorem 4.1. $\delta_{i,D+3-\ell}=\ln(\omega_{i,D+3-\ell})-\ln(\omega_{i,D+2-\ell})$ can be computed by $\mbox{$\mathbf{a}$}_{i}^{(\ell)}$ and thus $\mbox{$\mathbf{h}$}_{i}^{(\ell+1)}$ can be approximated via the FF layer following the $\ell$-th multi-head attention layer.

The final layer approximates an $A$-dimensional vector $P_{\pi_{\text{CTW}}}(\cdot|x_{1-D}^{n})=\sum_{l=0,\ldots,D}~{}\omega_{n,l}
\cdot\mbox{$\mathbf{p}$}_{n,s_{n,l}}(\cdot)$, by an FF layer taking input $\mbox{$\mathbf{h}$}^{(D+3)}_{n}=(\mbox{$\mathbf{s}$}_{n,M^{(1)}+1};\mbox{$
\mathbf{p}$}_{n,D};\mbox{$\mathbf{l}$}^{e}_{n,D};\delta_{n,D};\ldots;\delta_{n
,1};\mbox{$\mathbf{0}$};\mbox{$\mathbf{pos}$}_{i})$. The proof is now complete.
∎

Although transformers with sufficient FF layers can theoretically compute the optimal prediction as CTW, empirically, transformers of $2+D$ layers perform slightly worse in our experiments. This is likely due to the less-than perfect pretraining optimization and the limited representation capability of finite-width FF layers with ReLU activations. We also note that the proposed transformer construction may not be the only way to mimic CTW, however, we believe the first two layers do capture important universal features. We provide supporting evidences empirically in the sequel.

###### Theorem 4.2 .

###### Proof of Theorem 4.2 .

###### Theorem 4.3 .

###### Proof of Theorem 4.3 .

###### Theorem 4.4 .

###### Proof of Theorem 4.4 .

### 4.3 A Reduced Two-layer Construction

Figure: Figure 11: Hybrid Transformers: Effects of accumulative suffix counts and synthetic layers
Refer to caption: x8.png

We conduct experiments on the hybrid versions of transformers. Let ”TF 0-2” denote the canonical 2-layer transformer; ”TF 1-1” denote the transformer consisted of a constructed layer with output $\mbox{$\mathbf{h}$}_{i}^{(1)}$ equation 26, and a trainable transformer layer and a output layer taking $\mbox{$\mathbf{H}$}^{(1)}$ as input; and denote by ”TF 2-0” the transformer with 2 constructed layer with output $\mbox{$\mathbf{a}$}_{i}^{(2)}$ in equation 30, followed by a trainable FF layer (the FF layer in the second layer of the transformer) and an output layer.

We first study the key statistics behind the strong performance of two-layer transformers, as shown in the left panel in Fig. 11. Compared to ”TF 2-0” which is the constructed layers given previously, the version ”TF 2-0 w/o counts” does not contain $\mbox{$\mathbf{g}$}_{i-1,M^{\prime}}^{\leftarrow}$ or $\mbox{$\mathbf{pos}$}_{i}$ in $\mbox{$\mathbf{a}$}_{i}^{(2)}$; the version ”TF 2-0 total counts only” does not contain $\mbox{$\mathbf{g}$}_{i-1,M^{\prime}}^{\leftarrow}$ in $\mbox{$\mathbf{a}$}_{i}^{(2)}$ and $\mbox{$\mathbf{pos}$}_{i}$ is replaced by the total count $i$; ”TF 2-0 w/ all counts” replaces $\mbox{$\mathbf{g}$}_{i-1,M^{\prime}}^{\leftarrow}$ and $\mbox{$\mathbf{pos}$}_{i}$ with $\{\mbox{$\mathbf{n}$}_{n,s_{n,l}}\}_{l=0}^{D}$ and $i$. Even though their performances are rather clustered, we can make the following observations: 1) The performances degrade as more counting information is removed from the representation, and the counting information is clearly very important, 2) The performances of ”TF 2-0” and ”TF 2-0 w/ all counts” almost match exactly, indicating the main purpose of the backward statistics $\mbox{$\mathbf{g}$}^{\leftarrow}_{i-1,M^{\prime}}$ is to extract the counts, and 3) The performance of the original 2-layer transformer is similar to that of the constructed ”TF 2-0” and ”TF 2-0: w/ all counts” that those without less counting information.

We further study hybrid transformers with the first one or two being the constructed layers. As shown in the right panel of Fig. 11, transformers with 2 total layers and 4 total layers form two clusters, which provides strong evidence that the constructed layers are indeed replacing the first two layers of the original transformers in a functional manner. Moreover, the performances of transformers with a single constructed layer, such as ”TF 1-1” and ”TF 1-3”, are slightly better than those with two constructed layers, such as ”TF 2-0” and ”TF 2-2”, likely due to the flexibility in the remaining trainable transformer layers. Interestingly, for two-layer transformers, the hybrid versions can perform even better than the original transformer ”TF 0-2”, which we believe is because the latter is having difficulty extracting the exact statistics as those more readily available in the constructed layers.

## 5 Conclusion

We considered the in-context learning of transformers for VOMC sources. By drawing a close analogy of ICL and Bayesian universal compression, we leverage the CTW and PPM as baselines. Experimentally, we observe the performances of the trained transformers greatly surpass the performance PPM and are close to that of CTW even with just two layers under CTW priors; moreover, transformers are superior to CTW under non-CTW prior. To understand the mechanism of transformers’ ICL ability, we analyzed the attention maps and extracted two likely mechanisms. We then constructed the finite-memory context extension layer, and the statistics collection layer, corresponding to these two mechanisms, respectively. The latter collects both the forward and backward statistics, which are vital as theoretically demonstrated by a novel representation of the CTW optimal next-token prediction. We also provide empirical evidence that the statistics collected by the constructed second layer, in particular the counting statistics, are indeed necessary.

Although we empirically showed transformers can perform ICL-VOMC tasks, and constructed an idealized transformer to mimic the CTW algorithm, it is not clear whether a trained transformer will indeed utilize the upper layer mechanisms. Extending the existing approach [] to answer this question appears quite difficult, given the complexity of the constructed transformer and the underlying VOMCs; this is part of ongoing investigations.

## Peer Reviews

confidence: 4
contribution: 1
initial_rating: 3
presentation: 3
questions: I think this paper is sound! But it might be of interest to a specific, purely theoretical ML audience, and I do not think it contributes significantly to the existing work. Therefore, unfortunately I lean towards reject, and I suggest authors to consider a motivation and show that their findings can have some practical importance, otherwise the writing, theory and analysis seems complete to me.
soundness: 4
strengths: - The paper is math heavy but it has high readability.
- The paper finds ICL on VOMC less dependent on number of layers, which is interesting.
- Experiments guide theory to construct a manually crafted Transformer that gets better performance in this VOMC dataset
summary: This paper investigates in-context learning ability of auto-regresive transformers on data generated by variable order markov chains (VOMC). Previous work Edelman 2024 investigated fixed order markov chains (~ngram languages), Akyurek 2024 investigated uniform hidden markov models (probabilistic regular languages), and this is in the same line but learning a different class of probabilistic languages (i.e. probabilistic models). The paper experimentally shows the solutions of transformers are better than the Context Tree Weighting algorithm which is the optimal learning algorithm for a subset of VOMC problems. The paper then goes into proofs showing that the Transformer is theoretically capable of running CTWs.
weaknesses: - The paper does not explain why studying VOMC has any practical importance — what do we learn about Transformers? What is the additional information gained after Edelman 2024, Akyurek 2024 as they studied in-context learning of very similar probabilistic models.

- The paper has a very similar structure to Akyurek 2022, Akyurek 2024, Edelman 2024 with a slight change to the class of probabilistic models used. This hurts the novelty aspect of this paper.

- There is a long theory section for two different construction, I would keep only 4.3. I would move them 4.2 to the appendix and display the main theorems only.

---

confidence: 3
contribution: 2
initial_rating: 5
presentation: 2
questions: please refer to weakness
soundness: 2
strengths: 1. The study’s attempt to connect data compression techniques with transformer-based models is innovative and provides new insights into LLM behavior in sequence modeling.
2. The derivation of two specialized transformer structures based on CTW and PPM is well-motivated.
summary: This paper explores the in-context learning (ICL) capabilities of transformers for variable-order Markov chains (VOMC), viewing language modeling as a data compression problem. The authors benchmark transformer models against compression algorithms like context-tree weighting (CTW) and prediction by partial matching (PPM). Key findings include: (1) transformers effectively learn VOMC in context, outperforming PPM; (2) ICL performance is relatively insensitive to layer count, with even a two-layer transformer performing well; and (3) transformers can surpass CTW on non-CTW priors. The authors propose two transformer architectures to mimic CTW and explain observed behaviors, with a focus on the role of counting mechanisms in ICL.
weaknesses: 1. The experimental setup in the paper is limited, lacking comprehensive benchmarks for language modeling. More diverse and practical tasks, such as question answering and natural language understanding, should be used to confirm the robustness of the proposed transformer models.
2. The experiments were not validated on larger-scale pre-trained language models, such as models of the scale of GPT or LLaMA, which limits the study's practical relevance. Additionally, there is a lack of discussion on how these findings could be applied to mainstream LLM tasks.
3. The paper's readability could be improved.

---

confidence: 3
contribution: 3
initial_rating: 3
presentation: 2
questions: - How is the compression rate computed, and why can this rate exceed 1 for the PPM algorithm, as shown in Figure 4?
- How much of the training data in Section 3.1 is constructed, is the data sufficient enough for training, and what are the details of the training process, like the learning rate?
- What does the term "segment index" refer to in Figures 4 and 5?
- Typo: Line 356: "Fig 7" should be corrected to "Fig 6"
soundness: 3
strengths: - The paper presents an innovative perspective on understanding ICL by framing it as a context information compression task, which broadens the theoretical understanding of transformer capabilities.
- It offers empirical evidence and theoretical constructions that explain the observed phenomena (like Fig 6&7), providing insights into how transformers can mimic and even surpass traditional compression methods.
summary: The paper explores the in-context learning (ICL) capabilities of large language models (LLMs) by introducing a novel perspective of viewing language modeling as data compression. The study finds that transformers can effectively learn to compress VOMC in-context, outperforming traditional compression algorithms under certain conditions. Key phenomena observed include the resilience of transformers to layer variations and their ability to surpass CTW algorithms, particularly when non-CTW priors are used. The paper also provides theoretical frameworks to explain these observations.
weaknesses: - The work attempts to interpret ICL, but for readers familiar with ICL/LLM, the introduction of transformer attention (Sec 2.1) is somewhat redundant. Conversely, there is insufficient background information on CTW and related work, which are crucial for understanding the paper's context.
- The paper is challenging to follow without consulting the appendix, like Appendix A/B, which is essential for understanding the introduction and foundational concepts.
- There is a lack of real-world ICL example analyses, especially considering that the data used in the paper is different from the real data used in LLM ICL. Incorporating such examples, especially if the real ICL attention pattern mirrors those in Figures 6 and 7, would provide more robust validation.

---

confidence: 3
contribution: 2
initial_rating: 5
presentation: 3
questions: See weaknesses.
soundness: 2
strengths: 1. The authors found that transformers can learn to compress VOMC in-context, approaching the optimal CTW algorithm for appropriate CTW-priors.
2. The authors found that transformers do not require high network complexity. Even 2-layer transformers can perform well.
summary: This article examines how transformers learn variable-order MC. It extends previous research on the learning of fixed-order MC.
weaknesses: 1. Research on fixed-order MC helps us understand how the in-context learning capabilities of LLMs emerge. This is an important finding. Building on this, what key discoveries does this paper offer regarding variable-order MC? The authors' findings, including (1) transformers can learn VOMC in-context capabilities, and (2) transformers are more powerful than CTW, do not seem to bring significant new contributions or explanations.
2. To my understanding, the authors investigated the expressive capabilities of transformers. However, this has already been established. Previous work has found that even transformers with only one encoder layer and three decoder layers are Turing complete. Considering this, what stronger discoveries does the author's research on expressive capabilities bring compared to Turing completeness?
3. Why compare with CTW? Is it a sufficiently powerful framework?
4. What practical insights can be gained from the study of VOMC?

Meta-review: Based on the reviewers' feedback, I recommend rejecting this paper at this time. While the paper presents an interesting analysis of transformers' in-context learning capabilities for variable-order Markov chains through a data compression lens, several critical issues emerge. First, the paper's novelty is limited, as R1 points out that it largely follows the structure and approach of previous works Akyurek 2022, Akyurek 2024, Edelman 2024 with a slight change to the class of probabilistic models used. Second, the practical significance and insights gained from studying VOMC remain unclear, especially given that transformers' expressive capabilities are already well-established. Third, the experimental validation is limited, lacking comprehensive benchmarks and real-world ICL examples that would demonstrate practical relevance. While the mathematical treatment is sound and the paper is generally well-written, these fundamental concerns about novelty, practical relevance, and limited experimental validation make it difficult to justify acceptance.

Decision: Reject