DeciMamba: Exploring the Length Extrapolation Potential of Mamba

## Abstract

Abstract Long-range sequence processing poses a significant challenge for Transformers due to their quadratic complexity in input length. A promising alternative is Mamba, which demonstrates high performance and achieves Transformer-level capabilities while requiring substantially fewer computational resources. In this paper we explore the length-generalization capabilities of Mamba, which we find to be relatively limited. Through a series of visualizations and analyses we identify that the limitations arise from a restricted effective receptive field, dictated by the sequence length used during training. To address this constraint, we introduce DeciMamba , a context-extension method specifically designed for Mamba. This mechanism, built on top of a hidden filtering mechanism embedded within the S6 layer, enables the trained model to extrapolate well even without additional training. Empirical experiments over real-world long-range NLP tasks show that DeciMamba can extrapolate to context lengths that are 25x times longer than the ones seen during training, and does so without utilizing additional computational resources. We will release our code and models. https://github.com/assafbk/DeciMamba

## 1 Introduction

Figure: Figure 1: Document Retrieval Over SQuAD. We present a novel decimation mechanism tailored for Mamba, enabling it to process sequences that are x25 times longer than the ones seen during training. The purple line shows the training sequences length. Results are shown for DeciMamba-130M.
Refer to caption: x1.png

Lengthy sequences, which can span up to millions of tokens, are common in real-world applications including long books, high-resolution video and audio signals, and genomic data. Consequently, developing Deep Learning (DL) sequence models capable of effectively managing long contexts is a critical objective. Transformers Vaswani et al. (), despite their current dominance in general DL tasks, still face challenges in processing long sequences. Specifically, their quadratic complexity in sequence length makes them computationally demanding, restricting the ability to train them over long sequences and very large datasets.

In recent years, substantial efforts have been made in order to tackle this challenge.
The most significant advancements include efficient implementations that increase the model’s context length during training Dao et al. (); Liu et al. (), and context-extension methods Chen et al. (); Peng et al. () designed to effectively expand the context after training. However, recent studies suggest that long-range processing is still an unresolved problem Li et al. (); Liu et al. ().

One promising approach in this domain is the development of attention-free networks with sub-quadratic complexity, which can be trained more effectively over long sequences. In a recent line of work Gu et al. (, ); Gupta et al. (), the family of state-space layers has been introduced. These layers can be seen as theoretically grounded linear RNNs that can be efficiently computed in parallel via convolutions, thanks to a closed-form formulation of their linear recurrent rule. A recent advancement by Gu and Dao () presented Mamba, which builds on top of an expressive variant of SSMs called Selective State-Space Layers (S6). These layers match or exceed the performance of Transformers in several domains, such as NLP Pióro et al. (); Wang et al. (), image classification Zhu et al. (); Liu et al. (), audio processing Shams et al. (), genomic data Schiff et al. (), and more.

In this paper, we first explore the length-generalization abilities of Mamba and identify that they are relatively limited. Although Mamba layers are theoretically capable of capturing global interactions at the layer level, through a series of visualizations, analyses, and empirical measures, we show that the main barrier preventing Mamba from extrapolating is its implicit bias towards a limited effective receptive field (ERF), which is bounded primarily by the sequence length used during training. Secondly, based on the assumption that long-context data is usually sparse, we present DeciMamba, the first context-extension method specifically designed for S6. Our method relies on a dynamic data-dependent pooling method that utilizes a hidden filtering mechanism intrinsic to the Mamba layer. We leverage this mechanism to introduce a global compression operator, which expands Mamba’s ERF by discarding un-important tokens before each S6 layer. Our method significantly increases the effective context length of Mamba by several orders of magnitude while requiring a smaller computational budget.

Our main contributions encompass the following three aspects: (i) identify that Mamba has limited length-extrapolation capabilities, (ii) recognize via a series of visualizations, analyses, and empirical measures that although Mamba can theoretically capture global interactions via the recurrent state, its limited ERF prevents significant length-extrapolation. (iii) Building on this insight, we introduce DeciMamba, the first context-extension technique specifically designed for Mamba models. This approach leverages an existing filtering mechanism embedded within the S6 layer. As illustrated in Fig. 9, our method effectively enhances Mamba’s length-extrapolation abilities by up to eightfold, and is applicable to real-world long-context NLP tasks, as demonstrated in Fig. 1.

## 2 Preliminaries

In this section, the scientific context for discussion of long-range models is described and the necessary terminology and symbols are provided.
Such models evolve in two main directions: (i) first, by adapting transformers, the most dominant architecture today, to be more suitable for such tasks, or, alternatively, (ii) by developing architectures with sub-quadratic complexity in sequence length. Several modern examples include Hyena Poli et al. (), RWKV Peng et al. (), Hawk De et al. (), xLSTM Beck et al. (), and Mamba, the latter being the focus of our paper.

Mamba.
Given an input sequence $U=(u_{1},u_{2},\ldots,u_{L})\in\mathbb{R}^{L\times d}$ of length $L$ such that $u_{i}\in\mathbb{R}^{d}$, a Mamba block with $d$ channels is built on top of the S6 layer via the following formula:

$$ $G=\mathrm{\sigma}(\text{Linear}(U)),\quad X=\text{Conv1D}(\text{Linear}(U)),$ (1) $$

$$ $Y=S6(X),\quad O=Y\otimes G$ (2) $$

where $G$ represents the gate branch, $\otimes$ is elementwise multiplication, $\mathbf{\sigma}$ is the SILU activation, Linear and Conv1D are standard linear projection and 1-dimensional convolution layers. The S6 layer is based on a time-variant SSM, which can be elaborated by the following recurrent rule:

$$ $\vspace{-3pt}h_{t}=\bar{A}_{t}h_{t-1}+\bar{B}_{t}x_{t},\quad y_{t}=C_{t}h_{t} \vspace{-3pt}$ (3) $$

Where $X=(x_{1},x_{2},\ldots,x_{L})$ is the input sequence of a representative channel, $\bar{A}_{t}\in\mathbb{R}^{N\times N}$, $\bar{B}_{t}\in\mathbb{R}^{N\times 1}$, and $C_{t}\in\mathbb{R}^{1\times N}$ are the system, input, and output discrete time-variant matrices, respectively.
S6 conditions the discrete time-variant matrices based on the input as follows:

$$ $\Delta_{t}=\textit{Sft}(S_{\Delta}X_{t}),\quad B_{t}=S_{B}X_{t},\quad C_{t}=(S _{C}X_{t})^{T}$ (4) $$

$$ $\bar{A}_{t}=\exp(A\Delta_{t}),\quad\bar{B}_{t}=B_{t}\Delta_{t}$ (5) $$

such that $\Delta_{t}$ is the discretization step, Sft represents the softplus function, and $S_{\Delta},S_{B},S_{C}$ are linear projection layers.
Ali et al. () demonstrated that S6 layers, similar to attention models, can be interpreted as data-controlled linear operators. Specifically, the S6 layer computation can be represented using the following linear operator $\alpha$, controlled by the input (via Eq. 4 and 5):

$$ $\vspace{-3pt}Y=\alpha X,\quad\alpha_{i,j}=C_{i}\Big{(}\Pi_{k=j+1}^{i}\bar{A}_{ k}\Big{)}\bar{B}_{j}$ (6) $$

$$ $\begin{bmatrix}y_{1}\\ y_{2}\\ \vdots\\ y_{L}\\ \end{bmatrix}=\begin{bmatrix}C_{1}\bar{B}_{1}&0&\cdots&0\\ C_{2}\bar{A}_{2}\bar{B}_{1}&C_{2}\bar{B}_{2}&\cdots&0\\ \vdots&\vdots&\ddots&0\\ C_{L}\Pi_{k=2}^{L}\bar{A}_{k}\bar{B}_{1}\quad&C_{L}\Pi_{k=3}^{L}\bar{A}_{k} \bar{B}_{2}\quad&\cdots\quad&C_{L}\bar{B}_{L}\end{bmatrix}\begin{bmatrix}x_{1} \\ x_{2}\\ \vdots\\ x_{L}\\ \end{bmatrix}$ (7) $$

In this formulation, each output $y_{i}$ is a weighted sum of all inputs, where the ‘attention weights’ of all inputs $x_{j}$, i.e., the set $\{\alpha_{i,j}\}_{j=1}^{L}$, is data-driven.
We utilize this perspective to further investigate the effective receptive field of Mamba layers.

Context Extension & Length Extrapolation.
Over the years, several methods have been proposed to enhance the effective context length of transformers and improve their ability to extrapolate over longer sequences. Traditionally, length generalization is closely related to positional encoding. Pioneering work in the domain, introduced by Press et al. (), demonstrates that models built on top of original sinusoidal, rotary Su et al. (), and T5 bias Raffel et al. () positional encoding have poor length generalization abilities. It proposes Alibi, which mitigates this issue by promoting locality through the incorporation of distance-based linear biases into the attention matrix. A counter-intuitive study was conducted by Kazemnejad et al. (), which shows that transformers without positional encoding (NoPE) exhibit better length extrapolation capabilities in downstream tasks. Two more promising approaches are the very recent CoPE Golovneva et al. (), which utilizes context-aware positional encoding, and post-training positional interpolation Peng et al. (); Chen et al. ().

Alternatively, a recent direction involves architectural modifications to pre-trained models followed by short fine-tuning. Such works include LongLora Chen et al. (), which proposes shifted sparse attention, and Landmark Attention Mohtashami and Jaggi (), which applies attention in chunks and inserts global unique tokens into the input sequences between those chunks. Our method can be considered an application of this approach to Mamba models, rather than to traditional transformers. More related work is in App. B.

We note that in order to assess the long range performance of the model, in our experiments we measure perplexity only on the farthest labels of the context window, causing the perplexity values to be larger than their typical values (usually, all labels in the context window are aggregated).

## 3 Extrapolation Limitations of Mamba

In this section we explore the length-generalization capabilities of Mamba models. Specifically, we assess the effective receptive field (ERF) of S6 layers, a phenomenon that leads to poor information propagation when processing sequences that are longer than the ones trained on.

To investigate why Mamba fails at long sequence extrapolation we visualize Mamba’s hidden attention (Eq. 6, 7). In Fig. 2 we display the attention matrices of Mamba-130M after training it on the Passkey Retrieval task (Sec. 5) with a sequence length of 2K. We record the data for the matrices in layer 17, while evaluating sequences of length 2K and 16K. Notice that while the attention maps are very dense for the 2K sequence inference, the attention maps for the 16K sequence are much more sparse, and their elements vanish as we move towards the lower rows. This exhibits a limited effective receptive field (ERF), as information from the first tokens in the sequence does not propagate to the final tokens in the output sequence.

Figure: Figure 2: ERF Detected by the Mamba Attention Matrix (Eq. 7). We feed Mamba-130m with two sequences of different lengths, 2K and 16K, and show the attention matrices of layer 17. Mamba unintentionally learns an effective receptive field during training (right image, highlighted by the dashed rectangle), a behavior which limits its extrapolation abilities.
Refer to caption: x2.png

Measuring ERFs via Mamba Mean Distance. To understand the trend observed in Fig. 2, we introduce a quantitative measure called ‘Mamba Mean Distance’, which estimates the ERF of Mamba layers. This measurement is analogous to the receptive field in CNNs and the attention mean distance used in transformers, as described in the seminal work of Dosovitskiy et al. (). For a causal transformer model, the attention mean distance for the $i$-th output token is computed as follows:

$$ $\mathop{\mathbb{E}}_{j\leq i}d(i,j)=\sum_{j\leq i}\tilde{A}_{i,j}\otimes(i-j)\,,$ (8) $$

Where $\tilde{A}$ is the normalized attention matrix that defines a probability distribution over the distances for various tokens. We tailored this mechanism to S6 by leveraging the implicit attention representation, which we normalize using the following normalization function:

$$ $\mathbb{N}(x_{1},\cdots,x_{L})_{j}=\frac{|x_{j}|}{\sum_{i=1}^{L}|x_{i}|}.$ (9) $$

Since we are usually interested in the last tokens, and as we will see shortly, they are the first to suffer from this phenomenon, we find that it is sufficient to compute our metric for the last token only:

$$ $\vspace{-3pt}\mathop{\mathbb{E}}_{j\leq L}d(j,L)\approx\sum_{j\leq L}\mathbb{N }(\alpha)_{L,j}\otimes(L-j).\vspace{-3pt}$ (10) $$

Fig. 4 highlights the significance of this measure by presenting the implicit attention matrices of Mamba layers alongside their corresponding ‘Mamba Mean Distance’, which is depicted by the distance of the diagonal red line from the main diagonal of the attention matrix.

Figure: Figure 3: Mamba Mean Distance. Each panel contains an attention matrix along with its corresponding ’Mamba Mean Distance’, depicted by the distance of the red diagonal line from the main diagonal. The matrices are extracted from a pre-trained model of size 2.8B, trained on the Pile dataset Gao et al. ().
Refer to caption: extracted/5678656/figures/mambaDistance/Dist_MAMBA_attention_map_layer_11_channel_1.png

By introducing an empirical measurement for Mamba’s ERF, we can explore it more robustly. Fig. 4 depicts how the Mamba Mean Distance is influenced when increasing the input sequence length during training and inference. Here, Mamba-based language models with 80M parameters are trained across various context lengths for next-token prediction on the WikiText-103 benchmark Merity et al. (). We average the Mamba Mean Distance over all channels and layers using 100 test examples.

The left panel of Fig. 4 shows that the Mamba Mean Distance increases with longer context lengths during both training and evaluation. However, this does not take into account the length of the context that needs attending to. In the right panel, we normalize the Mamba Mean Distance by the sequence length during inference, revealing that the proportion of context utilized in practice decreases as the context length during evaluation increases. This phenomenon suggests that the limited length-extrapolation capabilities of Mamba models are due to a reduced ERF (represented by the normalized Mamba Mean Distance), which diminishes as the context length increases during evaluation.

To better understand this phenomenon, we return to the implicit attention defined in Eq. 7.
We note that the product of transition matrices $\prod_{k=j+1}^{i}\bar{A}_{k}$ includes more elements as the sequence length $L$ increases,
and can be written for the last row as:

$$ $\vspace{-3pt}\prod_{k=j+1}^{L}\bar{A}_{k}=\prod_{k=j+1}^{L}\exp(A\Delta_{k})= \exp(A\sum_{k=j+1}^{L}\Delta_{k})$ (11) $$

We note that this product always converges since $\Delta_{t}\geq 0$ and $A[i,i]<0$ by design. Yet, if it converges too fast, the attention element will collapse undesirably. To quantify the loss of information we focus on the attention element $\alpha_{L,1}$ due to the following reasons: (i) we are usually interested in the information at the end of the sequence; (ii) this element is the first in the row to collapse, capturing the first occasion of information loss because $\sum_{k=2}^{L}\Delta_{k}\geq\sum_{k=j+1}^{L}\Delta_{k}$ for all $L-1\geq j\geq 1$, and $A$ is always negative, so the power of its exponent will always be the smallest. We measure $\sum_{k=2}^{L}\Delta_{k}$ in Fig. 6 for varying evaluation context lengths L, per layer, averaged over the channels dimension. As can be seen in the figure, the values of $\sum_{k=2}^{L}\Delta_{k}$ increase exponentially fast in the most semantic layers (layers 16 and 17, see Passkey Retrieval in Sec. 5 for more details), leading to a fast collapse. Note that these are the layers where the worst ERFs are observed. The values of $\sum_{k=2}^{L}\Delta_{k}$ grow linearly in the other layers, which perform local processing (Fig. 15). Their decay is intentional.

A likely explanation for the limited length-generalization abilities is that during training, each SSM layer learns decay rates $A$ that are sufficient for processing training data of length $L_{train}$ but not flexible enough to provide effective length-extrapolation for lengths $L_{eval}>L_{train}$ . Specifically, if the decay rate is too high, long dependencies cannot be captured. Conversely, if the decay rate is too low, the state becomes “overloaded” with excessive information, which can obscure the important signals needed for effective processing.

Figure: Figure 5: Quantifying Mamba’s Information Loss by Measuring $\sum_{k=2}^{L}\Delta_{k}$ Divergence. To show Mamba’s sensitivity to increasing context lengths we measure the first occasion of information loss, as described in Sec.3. We observe that in the most semantic layers (16 and 17, see Passkey Retrieval in Sec. 5) $\sum_{k=2}^{L}\Delta_{k}$ diverges exponentially fast, causing a fast decay in its respective attention value, leading to the ERF observed in Fig. 2.
Refer to caption: x3.png

## 4 Method: DeciMamba

In Sec. 3 we identified that for a pre-trained model, the ERF of Mamba is dictated by the context size used during training $L_{train}$. This creates a blind spot for sequences that exceed $L_{train}$, as dependencies originating in the far input segments are not captured by the model, resulting in poor length generalization. To solve this problem we propose embedding a filtering mechanism within the pre-trained Mamba layers, with no need to re-train the model. The mechanism’s core task is to reduce the amount of tokens that the S6 layer processes, and it does so by discarding tokens of fewer importance. The entire method is visualized in Fig. 7 and encapsulates three aspects: (i) Decimation Strategy, (ii) Decimation Rate, and (iii) Decimation Scope.

Figure: Figure 7: DeciMamba: (Left) Schematic overview of DeciMamba. (Middle) By carefully inspecting the recurrent view of Mamba, we revealed the implicit filtering mechanism embedded in the recurrent gate and controlled by $\Delta$. (Right) We visualize the DeciMamba model, illustrating the decimation ratio and scope. The grey lines represent the sequence length at the input and output of each layer, and layers with empirically long ERFs are decimated.
Refer to caption: extracted/5678656/figures/deciMambaMethod.jpg

Decimation Strategy: The Role of $\Delta_{t}$
Unrolling Mamba’s recurrent rule (Eq. 12) reveals the link between the selective $\Delta_{t}$ and the token’s importance score for future tokens.

$$ $h_{t}=\bar{A}_{t}h_{t-1}+\bar{B}_{t}x_{t}=e^{A\Delta_{t}}h_{t-1}+\Delta_{t}B_{ t}x_{t}.$ (12) $$

When $\Delta_{t}\rightarrow 0$ the layer discards the input token and preserves the previous hidden state. When $\Delta_{t}>0$ the hidden state ’attends’ the input token (the attention is proportional to $\Delta_{t}$) and adds it to an attenuated version of the previous hidden state (this attenuation is also proportional to $\Delta_{t}$). We note that this is always the case because $\Delta_{t}\geq 0$ and $A[i,i]<0$ by design. Hence, $\Delta_{t}$ can be interpreted as the controller of the recurrent gate, determining which tokens should impact future tokens. Since Mamba ignores input tokens with small $\Delta_{t}$, it is natural to decimate them.

Decimation Ratio
For each decimating layer $s$, we propose to keep the Top-$P_{s}$ tokens with the largest mean $\Delta_{t}$ values (over the channels), where $P_{s}$ decreases gradually as we go deeper into the network according to the following formula:

$$ $P_{s}=L_{base}\cdot\beta^{s},\quad\beta\in(0,1),\quad L_{base}\in\mathbb{N}$ (13) $$

where $\beta,L_{base}$ are hyper-parameters representing a decay factor that controls the decimation rate (as we progress in depth) and the maximal length of the sequence after the first decimating layer. Sec.5.1 further discusses the selected pooling strategy.

Decimation Scope: Layer Selection
We turn to describe the decimation scope, which defines which layers should use the embedded decimation mechanism. We begin by explaining the guiding principles behind our method, followed by the criteria that reflects those principles.

Our goal is to expand the ERF of a pre-trained Mamba model. Traditionally, DL models focus on various scales of token interactions at different layers. Therefore, a natural design choice is to decimate in layers that already focus on long-range dependencies. This approach can potentially increase their ability to learn global dependencies without negatively impacting the layers that are associated with short-term features.

As a criterion for measuring the scale embedded within each layer, we measure the ERF of Mamba based on the Mamba Mean Distance defined in Eq. 10. We thus select the layers with the highest Mamba Mean Distance, with the number of selected layers being a hyper-parameter.

## 5 Experiments

We evaluate DeciMamba as a context-extension approach across multiple tasks. Initially, we demonstrate the long-range understanding and retrieval capabilities of our method in the NLP domain. Subsequently, we assess the retrieval abilities of our method using the Passkey test, and examine the language modeling capabilities of DeciMamba.

#### Document Retrieval

We demonstrate DeciMamba’s extrapolation abilities in a real-world long-range NLP task. In this task the model receives a query and $N_{docs}$ randomly assorted documents, and its objective is to return the id of the document that holds the answer to the query. Our data is sampled from SQuAD v2 Rajpurkar et al. (). We train both Mamba-130m and DeciMamba-130m to retrieve out of $N_{docs}=11$ documents (about 2k tokens), and evaluate their performance with $N_{docs}\in[11,300]$ (2k tokens to 60,000 tokens). The results are presented in Fig. 1. While Mamba is able to retrieve until $N_{docs}=40$ documents, it suffers from a sharp decline when the amount of documents is further extended. For $N_{docs}=50$ the input sequence length is about 10k tokens, and as can be seen in Sec. 5 (Passkey Retrieval) and in Fig. 14, Mamba-130m starts to suffer from ERFs around this region when trained on 2k tokens. On the contrary, DeciMamba is able to extrapolate to sequences that are more than x25 times longer than the ones seen during training ($\sim 250$ documents), without any additional computational resources.

Multi-Document QA.
Next, we stay in a setting similar to Sec. 5 (Document Retrieval), yet increase the level of difficulty by asking the model to answer the query in free text (instead of retrieving the id of the most relevant document). We train Mamba-130m and DeciMamba-130m on the same dataset and present the F1 score between the generated response and the ground truth answers in Tab. 1. As in the previous task, when the amount of documents is close to the amount trained on, the models perform quite similarly, with a slight advantage towards DeciMamba. When the document amount significantly increases we can see that DeciMamba develops a clear advantage. Yet, this time, due to the task’s difficulty, its performance decays as well. Note that Mamba’s and DeciMamba’s performance is relatively modest compared to prior work due to the use of smaller models, which limits the presented text generation capabilities.

Passkey Retrieval.
We fine-tune both Mamba-130M and DeciMamba-130M to retrieve a random 5-digit code hidden in a random location within a contiguous 2K token sample from Wiki-Text Merity et al. (). To test the models’ extrapolation abilities, during inference we increase the sequence lengths exponentially from 1K to 128K and record their performance for a variety of passkey locations within the context. Full implementation details can be found in Appendix A.1. As can be seen in Fig. 9, DeciMamba-130m significantly increases the extrapolation abilities of Mamba-130m from 16K to 128K, when trained on sequence lengths of 2k tokens only. Interestingly, we identify that the $\Delta_{t}$ values in Layer 16 of Mamba-130m capture the exact location of the passkey, as can be seen in Fig. 13. Using this finding, we display the distortion caused to the embedded sequence due to the ERF in Fig. 14. Tokens at locations < 10k have meaningful $\Delta_{t}$ values, yet tokens at locations > 10k have noisy $\Delta_{t}$’s, possibly due to the poor information flow caused by the ERF.

Language Modeling  Following Chen et al. (); Mehta et al. (); Chen et al. (), we evaluate our method on long-range language modeling using the PG-19 dataset in both zero-shot and fine-tuned regimes.

Zero-Shot. We test our method on the test set of PG-19 using the larger Mamba models (1.4b, 2.8b) in Fig. 9 (left). We observe that the selectivity scores learned during pre-training are quite effective and extend the context naturally without any training for both models. Furthermore, our method can maintain the low perplexity achieved in the short-context region. In the ablations section we further discuss our proposed decimation mechanism and show its benefit w.r.t other alternatives.

Fine-Tuning. We display DeciMamba’s performance on PG-19 perplexity in Fig. 6. We train both Mamba-130M and DeciMamba-130M with a sequence length of 2K and test their extrapolation abilities. The full training details can be found in Sec. A.4 in the appendix. While Mamba can extrapolate to context lengths that are at most x5 times longer than the training sequences, DeciMamba can extrapolate to sequences that are about x20 times longer, without any additional computational resources. Furthermore, we plot a lower bound by calculating the perplexity of a Mamba-130M model that was trained on the same context length it evaluates on (each point on the green curve is a different model). We observe that DeciMamba is close to the lower bound and diverges from it quite slowly, while utilizing significantly less computational resources. Nevertheless, for train sequences longer than 30K the ‘lower bound’ models reach an Out Of Memory (OOM) error (Nvidia RTX-A6000, 48GB of RAM), further emphasizing the importance of good extrapolation abilities when scaling to longer sequences.

Figure: Figure 8: Passkey Retrieval. DeciMamba’s global pooling layer adapts the input sequence’s length to the effective receptive field learned during short-sequence training. This allows the model to extrapolate to sequences that are significantly longer. Results for Mamba-130m.
Refer to caption: x5.png

**Table 1: Multi-Document QA. The table holds the F1 score between the ground truth annotations and the predictions of Mamba-130m and DeciMamba-130m (+Deci) across different number of documents. Both models were trained using 11 documents.**
| #Docs | 5 | 10 | 20 | 40 | 60 | 80 | 100 | 120 | 140 | 160 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Mamba | 23.5 | 25.3 | 22.8 | 23.6 | 25.8 | 19.3 | 7.5 | 4.1 | 1.1 | 0.6 |
| +Deci | 25.6 | 26.2 | 24.4 | 25.3 | 22.74 | 19.1 | 18.1 | 12.9 | 10.0 | 5.0 |

### 5.1 Ablations

Layer Selection  We ablate our layer selection methodology, as it has significant affect on the model’s performance (Figure 10). Each point on the curve represents the score achieved by a DeciMamba-130M model in the Passkey Retrieval task when trained on sequences of length 2K. The only difference between the models is the first decimating layer (x axis). We see that when the decimating layer is too shallow (e.g. layer 8), the model fails completely. As we increase the minimal decimating layer we observe a large increase in performance, until reaching the climax at layer 12. This result aligns with the fact that the $\Delta_{t}$ distribution is farther from 0 in Mamba’s early layers (all tokens are important). We hypothesize that the tokens still don’t have a strong representation at this stage, hence it makes less sense to decimate w.r.t their $\Delta_{t}$ value. After layer 12 the performance of DeciMamba starts to drop, and stabilizes at the vicinity of the baseline Mamba model. At this region we start decimating too late, as some long-dependency layers suffer from ERFs when processing the longer Passkey Retrieval sequences. The final layers (21-23) also have larger $\Delta_{t}$ values, so they should not be decimated as well. We hypothesize that these layers ’decode’ the processed embeddings back into token distributions, so the intermediate representations are yet again not fit for semantic decimation.

Figure: Figure 10: Layer Selection Ablation. Score achieved by DeciMamba-130M in the Passkey Retrieval task when trained on sequence lengths of 2K. All models differ by the first decimating layer (x axis) and stop decimating at layer 20. The result shows the model’s sensitivity to the selection of decimating layers.
Refer to caption: x8.png

Pooling Strategy
We show the importance of the proposed Top-$P_{s}$ pooling strategy in the following ablation study. Suppose we select a different pooling strategy, Top-$K\%$, which keeps the top $K\%$ tokens with the largest mean $\Delta_{t}$ values (over the channels dimension). We train a DeciMamba-130m model for the Passkey Retrieval task on sequences of length $L_{train}=2K$, with $K=50\%$ and decimation layers [12,…,20]. As can be seen in Fig. 11 (Appendix), Top-$K\%$ extends Mamba’s extrapolation abilities from 8K to 32K, yet does not do as well as Top-$P_{s}$ which extends to 128K.
While Top-$K\%$ decimation decreases the sequence length greatly (the output is x512 times shorter), during extrapolation each SSM layer still faces input sequences that are much longer than the ones it has seen during training, as demonstrated in Fig. 12.
We further explain this result; During training Layer 17 saw sequences of length 65 ($L_{train}=2K$, followed by a decimation rate of 50% in each layer from layer 12). During inference it sees sequences of lengths 65 and 1002 (where $L_{eval}=2K,32K$, left and right images, respectively). Since the sequence length at layer 17 of the latter (1K) is much longer than the one it saw during training (65), the extrapolation is limited by an ERF (right image, dashed orange shape). This shows the importance of keeping the lengths of the inputs to each decimating SSM layer similar to the ones seen during training, as done by Top-$P_{s}$.

Decimation Mechanism.  To emphasize the benefit of pooling w.r.t the values of $\Delta_{t}$, we examine two additional decimation mechanisms: max-norm decimation (tokens with maximal norm are kept) and random decimation (tokens are randomly kept). We equip Mamba-1.4b with each of the decimation mechanisms (decimation layer = 12, $L_{base}=8000$), and compare each model’s zero-shot perplexity in Fig. 9 (right). Max-norm pooling achieves a similar trend to $\Delta_{t}$ pooling (DeciMamba), yet performs somewhat worse. The result suggests that $\Delta_{t}$ is a better candidate for pooling, but also shows that the token’s norm also holds some information about its importance. We hypothesize that a method that combines both might achieve better performance than any one alone, but leave this question open for future work. Random pooling induces strong distortion to the embedded sequence, yet achieves better perplexity for longer contexts. This surprising result demonstrates how sensitive Mamba is to ERFs - in longer sequences, it is actually better to randomly decimate the sequence rather than process its full length.

## 6 Conclusions

In this paper, we explore the length-extrapolation abilities of S6 layers. Our first contribution is the characterization of the ERF of S6. This characterization reveals that the ERF of Mamba is significantly constrained by the context length during training, which is counterintuitive given that Mamba theoretically has an unbounded receptive field due to its recurrent selective memory. Based on these insights, we develop DeciMamba, a unique data-dependent compression operator that is built on two key insights: (i) There exists a hidden filtering mechanism within the Mamba layer, manifested by the selective time-steps $\Delta_{t}$, which can be interpreted as the controller of the recurrent gate. (ii) Long-range and short-range interactions between tokens are captured by different layers in the model, which can be identified using our Mamba Mean Distance metric.

Looking ahead, we plan to explore different transformer context-extension methods, including length-extrapolation PE Press et al. (); Golovneva et al. (), hierarchical models, and architectural improvements Sun et al. (). Furthermore, we intend to extend our analysis to other layers beyond S6, e.g., RWKV, xLSTM, and more.

## 7 Limitations

Our model modifies a pretrained Mamba model but does not propose an improved Mamba architecture to address the underlying issue. Despite empirical evidence demonstrating the effectiveness of our decimation-based method in capturing long-range interactions and its efficiency, the approach can be suboptimal. For example, pooling and compression methods may miss critical information in challenging scenarios. Therefore, designing an improved Mamba variant with enhanced length-generalization abilities that can effectively capture global interactions within a single layer (without pooling the sequence) is an important next step.

## 8 Ethics Statement

This work analyzes and improves the performance of large language models (LLMs) for long context understanding, which is crucial when deploying them in real-world systems. This improvement is anticipated to have a positive impact on the use of LLMs in society. However, we acknowledge that LLMs could propagate biases. We emphasize the necessity of further research into these biases before our work can be applied reliably beyond the research environment.

## Acknowledgments

This work was supported by a grant from the Tel Aviv University Center for AI and Data Science (TAD), and was partially supported by the KLA foundation. We would like to thank Yael Vinker and Maor Ivgi for fruitful discussions and valuable input which helped improve this work.

## Appendix A Experimental Details

All model checkpoints are taken from the Hugging Face Model Hub(^1^11https://www.huggingface.co/models):

- •
state-spaces/mamba-130m
- •
state-spaces/mamba-370m
- •
state-spaces/mamba-790m
- •
state-spaces/mamba-1.4b
- •
state-spaces/mamba-2.8b

Our code is based on the official Mamba implementation. (^2^22https://github.com/state-spaces/mamba)

### A.1 Passkey Retrieval

Each model is trained for 5 epochs with a learning rate of 1e-4, gradient clipping of 1, batch size of 32 (used batch accumulation) and AdamW optimizer Kingma and Ba () with weight decay of 0.1. In each epoch the models train over 6144 sequences of length 2K. For DeciMamba-130M we use $L_base=2K$, $\beta=0.5$, $decimating_layers=[13,...,21],min_seq_len=20$.

### A.2 Document Retrieval

We train each model with data from SQuAD v2 Rajpurkar et al. (), which provides examples in the form of (Query, Document, Answer). Our training samples have the following form: <$Query$>; $N_{docs}\times$<$Document$>; <$Answer$>, where <$Document$> can be either the golden document (which holds the answer to the query) or one of $N_{docs}-1$ randomly sampled documents. <$Answer$> holds the id of the golden document. In our setting $N_{docs}=11$, the order of the documents is random, and the query and respective document id are appended to the beginning of each document. During Evaluation we use the same setting but vary the value of $N_{docs}$, between 11 and 300. We note that an average document in SQuAD has a length of about 200 tokens, so our average training sample has about 2,000 tokens, and the evaluation samples vary between 2,000 tokens to 60,000 tokens. We train for one epoch with 300 steps, use a learning rate of 1e-4, gradient clipping of 1, batch size of 64 (used batch accumulation) and AdamW optimizer with weight decay of 0.1.

Figure: Figure 11: Pooling Strategy Ablation - Results. The figure compares two pooling strategies, Top-$P_{s}$ (ours) and Top-$K\%$. As shown, the Top-$K\%$ approach lags behind the Top-$P_{s}$ approach, demonstrating that our strategy allows the model to extrapolate to significantly longer sequences. Results are for Mamba-130m.
Refer to caption: x9.png

Figure: Figure 12: Pooling Strategy Ablation. Top-$K\%$ pooling leads to a limited ERF in layer 17. The size of the attention map is affected by the input sequence length: for $L_{eval}=2K$ layer 17 will process 65 tokens (left) and for $L_{eval}=32K$ it will process 1K tokens (right). Since $L_{train}=2K$, layer 17 has only seen training sequences of length 65, therefore suffers from an ERF when $L_{eval}$ increases (right, dashed orange shape).
Refer to caption: x10.png

### A.3 Multi-Document Question Answering With Free Text Response

We operate in a similar setting as in Section A.2, but instead of predicting the tokens of the id of the relevant document we let the model generate a free-text response and measure it’s F1 score w.r.t a set of ground truth answers. We train each model for one epoch on the full SQuAD train set (about 90,000 examples when leaving out the samples intended for negative sampling, which do not have a ground-truth answer). We found that the optimal decimation parameters are decimation_layer = 14, $L_{base}$=2000 during training and $L_{base}$=7000 during evaluation. We intentionally decreased Lbase during training so the model could experience decimation during the training period ($L_{train}$ was a bit higher than $L_{base}$), because otherwise the training of DeciMamba and Mamba would have been identical.
We use a learning rate of 1e-4, gradient clipping of 1, batch size of 64 (used batch accumulation) and AdamW optimizer with weight decay of 0.1.

### A.4 PG-19 Perplexity

We train each model on a total of 100M tokens with a learning rate of 1e-4, gradient clipping of 1, batch size of 250 (used batch accumulation) and AdamW optimizer with weight decay of 0.1. During training we sample a single window from each example and train on it (For the extrapolating models the window length is 2K, for the lower bound models the window length is equal to the context length trained on). During evaluation, for each example we evaluate 10 windows with a maximal constant stride. We evaluate only the last 100 labels in each window, which represent the extrapolation abilities of the model at sequence lengths in the range of [$ctx_len-100,ctx_len$], providing an approximation to the model’s performance at the wanted $ctx_len$. For DeciMamba-130M we use $L_base=2K$, $\beta=0.83$, $decimating_layers=[12,...,20],min_seq_len=20$. During evaluation we keep the same parameters except setting $L_base=8K$. Additionally, in this specific task DeciMamba was trained with a similar, yet not identical, Language Modeling (LM) loss. We break the labels sequence (length = 2K) into two chunks. The first 1K labels are trained conditionally on the first 1K tokens of the sequence (like vanilla LM). The last 1K labels are trained conditionally on the whole sequence (2K), and DeciMamba was configured to compress the first 1K input tokens. This way we are able to train DeciMamba to compress context while training on each label in the sequence, making the training much more efficient. We also experimented with chunking the labels into more than two chunks, but only experienced a slowdown in computation while achieving similar performance. For the lower bound models we had to reduce the amount of training steps in order to constrain the training to 100M tokens. Specifically, for each context length, we followed the following formula: $num_of_steps=100M/(batch_size*ctx_len)=100M/(250*ctx_len)$. For the Zero-Shot perplexity test for the 1.4b model we used Layer 12 for decimation and $L_{base}=4000$. For the 2.8b model we used Layer 22 for decimation and $L_{base}=4000$.

Figure: Figure 13: Demonstrating the ‘Importance-Scoring’ Abilities of $\Delta_{t}$. We evaluate Mamba-130M on the Passkey Retrieval task, and record the values of $\Delta_{t}$ for all channels of layer 16. Each pair of images is identical, except that the left one marks the location of the passkey with a dashed pink line. The horizontal and vertical axes indicate the token number and the channel respectively. As can be seen from the two cases examined above, the $\Delta_{t}$ activation captures the needle location successfully, demonstrating the effectiveness of its ‘importance scoring’ mechanism.
Refer to caption: x11.png

Figure: Figure 14: Measuring the Effects of Limited ERFs. We show the $\Delta_{t}$ values across the channels for layer 16 in the Mamba-130M model, examined on different context lengths. The horizontal and vertical axes indicate the token number and the channel respectively. As can be observed from the results above, the passkey can be detected clearly until the ERF ends (for $t>10K$).
Refer to caption: x12.png

Figure: Figure 15: Normalized Mamba Attention Map. Displayed in log scale for each layer of the Mamba-130M model.
Refer to caption: x13.png

## Appendix B Other Related Work

### B.1 Long Range Transformers.

Transformers have emerged as highly effective models for various tasks, yet their widespread adoption has been constrained by their limited long-range modeling capabilities. Thus, applying transformers effectively to long-range data remains a central challenge in DL, particularly in NLP. A primary factor in this challenge is that the effective context of transformers is dominated by the context observed during training, which is limited because training LLMs on datasets with billions of tokens across lengthy sequences is computationally demanding. Hence, three main approaches have been developed to tackle this problem: (i) creating efficient variants of transformers that allow an increase in the length of sequences during training. (ii) Context extension methods, which enable training on short sequences and evaluation on long sequences, and finally, (iii) hierarchical models that rely on pooling, chunking, and compression. Despite these extensive efforts, several recent studies indicate that high-quality handling of long text remains an unresolved issue Liu et al. (); Li et al. ().

Efficient transformers.
Over the years, many approaches have been proposed for making transformers more efficient Tay et al. (); Fournier et al. (). The two most prominent directions are hardware-aware implementations such as flash-attention Dao et al. (); Dao () and ring-attention Liu et al. (), which accelerate computations over long sequences by several orders of magnitude. Additionally, developing efficient attention variants with sub-quadratic complexity has become very popular. Two notable examples are Linformer Wang et al. (), which utilizes a low-rank attention matrix, and Performer Choromanski et al. (), a variant that approximates the attention operator through a kernel function.

## Peer Reviews

confidence: 4
contribution: 3
initial_rating: 6
presentation: 2
questions: I asked my questions in the weakness section.
soundness: 3
strengths: Overall, I like this paper, I think that Mamba is a very appealing method due to its low inference cost and getting methods that allow extending the context length for Mamba is a very important question. I appreciate the fact that the authors considered diverse benchmarks and the gap between Mamba and Decimamba is pretty consistent in some cases. I also appreciated the scientific approach in the paper that consists in isolating  the problematic component in Mamba and proposing a method to alleviate the issue.
summary: This paper proposes a new method to extend the context length of Mamba. The authors start with an explanation of why Mamba in its original form cannot extend the context length. They propose viewing the S6 block as applying an “attention operation” (Section 2) and based on these attention weights, they compute the Mamba mean distance to measure the effective receptive field of Mamba (Section 3). They basically show that the ERF decreases as the context length at inference time increases and that the main culprit is the fast decrease of the sum of discretization steps. To tackle this issue, they introduce Decimamba, a filtering mechanism that discards tokens of lesser importance (Section 4). They finally show on multiple information retrieval benchmarks that the method better performs on long contexts than Mamba.
weaknesses: I have a few concerns regarding this paper that I list below: 

- **Hyperparameter choices**: I agree with the fact that the fast decay of the sum of the discrete time steps may explain the lack of length generalization. However, the approach looks a bit hacky in that it introduces multiple novel hyperparameters: the decay factor, the maximal length of the sequence after the first decimating later and the number of layers to decimate. And it does not seem very clear how to make these choices without a gridsearch?
- **Ablations**: have you tried to do an ablation with respect to the number of layers to be decimated or with respect to the decay rate? 
Writing should be improved: I found the decimation strategy in Decimamba (Section 4) pretty hard to follow. I think that this should be better explained. 
- **Tasks where Decimamba offers much higher gains?**: we see that Decimamba leads sometimes to big improvements (Squad and Passkey retrieval) but on Multi-Document QA, the decay of Mamba seems to also be important. Do you have an explanation/intuition of the type of tasks where Decimamba leads to substantial improvements?



Minor points:

**Improving the introduction**: I think the author should maybe better explain the Decimamba method in the introduction (and maybe add Figure 5 to the introduction?). 
- **Lack of length generalization of Mamba**: I was a bit confused about the fact that the authors were surprised by the lack of length generalization of Mamba. I agree with the authors that compared to Transformers, the context cache (the hidden states) do not grow with the context length and thus Mamba can scale the context length to infinity. However, this state is **bounded** and thus the model cannot store all the information it may need . In an information retrieval setting, when the number of documents is large, it is easy to imagine that Mamba has trouble deciding which tokens to store. Anyway, this all to say that the authors should maybe highlight that one of the factors explaining the poor length generalization is the small state space size. I think that this is aligned with the method proposed by the authors in that it looks to decimate some non-important tokens that may be captured in the hidden state.
- **Influence of hidden state size on length generalization**: one thing that i am curious about is: have you tried to study the length generalization of models of similar scale but with one of the models having a bigger state space?
- **Comparison with Transformers**: have you tried to run Transformers in the benchmarks of Section 5? Just curious to see the gap of DeciMamba with Transformers.
- **Out of memory**: Maybe I would add a comment saying that the OOM happens in Figure 6 because the complexity at **training time** is O(L). Most people may have in mind the complexity of Mamba at inference time, that is independent of the context length and may be confused by the OOM you encounter. 
- **Typo**: In equation (8), i think the letters "j" and "L" were swapped. It should be $d(L,j)$.

---

confidence: 4
contribution: 2
initial_rating: 3
presentation: 2
questions: - The relationship between distance and performance shown in Fig 1 appears counterintuitive. If Mamba struggles with long-distance relationships, why does the performance degradation manifest primarily in middle lengths rather than showing a clear diagonal boundary from top-left to bottom-right between the red and green regions? Could this suggest a more complex underlying mechanism?
- Given the increasing importance of long-text generation in applications like complex reasoning and creative writing, have the authors explored possibilities of extending this method beyond prefilling to support long-text generation scenarios? It would be benefitial to discuss any challenges the authors foresee in extending the approach to generation tasks.
- The experimental setup shows variations in model selection across different figures and analyses (e.g. Fig 3 and Fig 4). Could the authors provide more detailed justification for these choices and discuss how they might impact the generalizability of the findings?
- Regarding the Mamba Mean Distance results in Fig 4, the findings don't definitively prove that Mamba's long-text capability decreases with length, as this metric wouldn't necessarily scale linearly with sequence length. Are there similar studies for attention-based architectures?
soundness: 2
strengths: - The investigation of token importance scoring in the context of Mamba represents a valuable contribution to the field, especially given the growing interest in alternatives to attention-based mechanisms
- The method achieves substantial improvements while maintaining implementation simplicity, making it readily applicable in practical scenarios
summary: This paper investigates Mamba's length extrapolation capabilities through a systematic analysis approach. The authors introduce the Mamba Mean Distance metric as a novel way to quantify and analyze Mamba's ability to model long-range dependencies. Their findings reveal inherent limitations in Mamba's capacity to handle longer sequences effectively. To address this challenge, they propose a selective token processing mechanism leveraging the delta t parameter from the Mamba formula. This approach intelligently filters tokens by retaining those with larger delta t values, effectively aligning the input complexity with Mamba's modeling capacity. The method is specifically designed for the prefilling phase and demonstrates promising improvements in Mamba's long-text processing capabilities.
weaknesses: - Limited scope of application: The method's restriction to the prefilling phase significantly limits its practical impact, especially considering the increasing demand for both long-text prefilling and generation in modern applications
- Potential information loss: The token discarding approach may have unintended consequences in scenarios requiring comprehensive context understanding. This is particularly problematic in tasks like document question-answering, where discarded tokens during prefilling might be crucial for subsequent generation phases
- Incomplete solution to fundamental limitations: While the approach provides a practical workaround, it doesn't address the underlying limitations of Mamba in processing long sequences. A more thorough analysis of the Mamba Mean Distance metric could potentially lead to more fundamental solutions

---

confidence: 5
contribution: 2
initial_rating: 3
presentation: 2
questions: Please refer to the Weaknesses.
soundness: 2
strengths: 1. The proposed method is straightforward and can be directly combined with Mamba to improve the length generalization abilities.
2. The authors analyze the shortcomings of Mamba in terms of its length generalization abilities.
summary: This paper presents the limitations of Mamba in terms of length generalization and proposes an algorithm that combines token dropping with the Mamba architecture to effectively enhance its length generalization capabilities.
weaknesses: 1. The experimental results are limited. The authors only combine the method with the Mamba model and verify the effectiveness of their method. It would be more convincing if the method can be validated on a broader range of SSM-based and linear-attention-based models.
2. The experimental results are not satisfactory. As shown in Table 1, DeciMamba fails to achieve more than a 10% LongBench score on most datasets. In contrast, models with a context window size of only 4k, as reported in the original LongBench paper, often perform better (e.g., Llama-2-7B-chat has an average score of 31 on English tasks). Additionally, for simpler long-context tasks like Passkey, the authors mention that DeciMamba requires fine-tuning to handle them effectively.
3. The presentation of the paper could be improved. For instance, proper citation formats (\citep and \citet) should be used; table captions should appear above the tables; and in Table 1, the DeciMamba entry is missing the LB score for the LCC dataset.

---

confidence: 3
contribution: 4
initial_rating: 8
presentation: 4
questions: - How does the DeciMamba architecture compare to Mamba at short context length tasks? Ie, is there a tradeoff between performance on short and long context tasks?
soundness: 4
strengths: - The paper introduces the phenomenon of "limited effective receptive field" which could be useful for future work studying the Mamba architecture
- The proposed design is well motivated by the identified ERF phenomenon
- The proposed architecture shows consistent improvement over Mamba in long context range experiments
- The paper includes effective visualizations, especially Figure 2
summary: This paper studies the question of how to understand and address the limitations of length generalization capabilities of the Mamba architecture. The paper introduces ERF, the effective receptive field, and shows that Mamba is biased towards sequence lengths seen during training. The authors then introduce DeciMamba to extend length generalization capabilities by limiting the number of tokens that the S6 layer processes.
weaknesses: - Most of the related work on length generalization is for transformers. Is there any work on this for SSMs? I'm not sure exactly where this falls in the literature.

Meta-review: This paper studies the length generalization ability of Mamba and proposes a way to improve it. The paper proposes a measure named Mamba mean distance to capture the length of “effective receptive field (ERF)”, and identifies that Mamba extrapolating to longer sequence length suffers limited ERF, which leads to degraded performance. The authors then propose discarding tokens considered unimportant by Mamba, by choosing only tokens with large averaged discretization step size $\Delta_t$. Notably, the proposed method does not require re-training the model. The paper presents extensive numerical evaluation and shows consistent improvement of the proposed method DeciMamba over Mamba.

The paper tackles a fundamental problem in the study of SSMs and sequence processing models in general. Over diverse benchmarks and model size, the paper demonstrates consistent improvements in terms of context extension. Although the paper does not provide a complete solution to limited ERF, I view DeciMamba as a good “engineering solution” to improve existing Mamba models.

There were concerns raised and some reviewers were negative about the paper. One shortcoming of the proposed approach is that the proposed method only applies to the specific model Mamba, which is true. The authors clarified that while this is indeed the case, the ideas proposed in the paper can be applied to evaluate and improve other models (Appendix E). Another concern was that the proposed method only considers pre-filling stage, not decoding stage; the authors outlined ways to apply their method to the decoding stage and showed that applying DeciMamba for decoding yields limited benefit at least in the benchmark considered (Although I think the technique may become useful in tasks where we need to generate sequences longer than those seen in training). 

Overall, the authors put extensive efforts during the rebuttal phase to respond to reviewers’ questions and reflect reviewers’ suggestions to the revised manuscript. The paper is now supplemented with richer contents, and I believe most of the issues raised by the reviewers were properly addressed. Hence, I recommend this paper for acceptance.

Decision: Accept (Poster)