Long-Context Demonstration Selection Using State Space Models

Ziniu Zhang, Zhenshuo Zhang, Ruoxuan Xiong, Gene Cooperman, Hongyang R. ZhangarXiv 2026

TL;DR

This paper introduces a novel framework for selecting the best examples (demonstrations) for in-context learning in long-context scenarios. By distilling expensive, quadratic-cost Transformer models into linear-cost State Space Models (SSMs), the authors achieve a 14.2× reduction in computational overhead and a 6.48% improvement in accuracy compared to existing selection methods.

What Problem Does This Paper Address?

In-context learning (ICL) allows large language models (LLMs) to solve new tasks simply by seeing a few examples in the prompt. However, picking the right examples from a large pool is difficult because the effectiveness of one example often depends on which others are present.

The standard way to find the best subset is to test many combinations, but this hits a massive computational wall: Transformers have a quadratic inference cost relative to sequence length. As prompts get longer (thousands of tokens), evaluating hundreds of candidate subsets becomes prohibitively expensive. The authors aim to break this bottleneck by making the evaluation process linear rather than quadratic.

Methods

The authors propose a two-stage approach, illustrated in the overview below:

Figure 1: Overview of our approach: Given a set of candidate demonstrations and query-target pairs from an unknown distribution, our approach learns a set of state space models through distillation from a pretrained model. Then, we use the extracted embeddings from the state space models for demonstration selection. We sample multiple subsets of demonstrations and evaluate the concatenated subset embeddings. We aggregate the subset losses to an affinity score for every demonstration and select the top-k demonstrations ranked by the scores.
  1. Algorithm 1: Learning the SSMs (Distillation). Instead of using the full Transformer to evaluate every candidate subset, they train a group of small State Space Models (SSMs) to mimic the Transformer's behavior. They partition the Transformer's layers into groups and assign an independent SSM to each. These SSMs use the HiPPO-LegS matrix to compress long sequences into a compact hidden state, which is then projected into a small set of "virtual" Key-Value (KV) tokens. These tokens act as a highly compressed summary that the original Transformer can process directly.
  2. Algorithm 2: Demonstration Selection. With the fast SSMs in place, the authors use a randomized estimator. They sample many subsets of demonstrations, pass them through the distilled SSMs to get their compressed representations, and evaluate their performance on a validation set. They then calculate an "affinity score" for each individual demonstration based on how well the subsets containing it performed. Finally, they select the top-k demonstrations with the highest scores.

Datasets

The researchers validated their approach across a wide variety of tasks:

  • Synthetic Tasks: Linear and non-linear regression to test the fundamental selection capabilities.
  • Text Classification: SST-2 (movie reviews) and Poem Sentiment.
  • Reasoning & Arithmetic: Coin Flip (tracking states), Edge Existence (graph reasoning), and Modular Addition.
  • General Benchmarks: MMLU (multitask knowledge) and GSM8K (grade-school math word problems).

Key Insights and Ideas

  • The KV Cache is Compressible: A major "aha" moment was discovering that the Key-Value (KV) cache in Transformers is dominated by low-order components. As shown in Figure 2, the coefficients of the KV cache decay rapidly when projected onto a Legendre basis. This confirms that SSMs, which are designed to capture these low-order structures, are perfect for compressing long contexts.
Figure 2: Mean squared discrete Legendre coefficients of KV caches on Qwen-7B-Instruct and Llama-3-8B- Instruct with G=4 layer groups and k=50 demonstra- tions. The coefficients decay rapidly across groups, and the KV cache is dominated by low-order HiPPO-LegS components.
  • Linear Scaling is the Key: By replacing the $O(T^2)$ Transformer pre-filling with $O(T)$ SSM scans, the selection process scales linearly with the number of demonstrations. This makes "many-shot" ICL (using hundreds or thousands of examples) practically feasible.
  • Virtual Tokens as a Bridge: Mapping SSM states back into the Transformer's KV space allows the distilled model to be "plug-and-play" with the original pretrained LLM without needing to retrain the entire massive model.

Key Results

  • High Fidelity: The distilled SSMs are incredibly accurate, incurring an approximation error of less than 0.7% relative to the full Transformer output.
  • Efficiency Gains: The method reduces FLOPs (floating-point operations) by 14.2× compared to dense inference. In synthetic settings, the overhead reduction reached 15.7×.
  • Performance Boost: On downstream tasks, the selection algorithm improved accuracy by an average of 6.48% over baseline methods like BRIDGE.
  • Scalability: As shown in the runtime scaling plots, the proposed method (Alg. 1) maintains near-linear growth in processing time as the number of demonstrations ($k$) increases, while full inference explodes quadratically.
Figure 3: Evaluation of our approach for linear and non- linear functions. The top panel provides a comparison with random-k and top-k selection methods. The lower panel illustrates the computational costs relative to full inference (denoted as not optimized).

Limitations and Future Work

  • Distillation Requirement: Unlike "training-free" methods, this approach requires a distillation phase to train the SSMs for a specific model and task category.
  • Fixed SSM Structure: The current work uses a fixed HiPPO recurrence. Future work could explore more flexible, data-dependent SSM architectures (like Mamba) to further improve compression.
  • Trajectory Optimization: The authors suggest that these techniques could be extended to automated trajectory optimization—essentially picking the best sequence of actions or thoughts in complex reasoning chains.

Summary updated

BibTeX
@misc{zhang2026long,
  author = {Ziniu Zhang and Zhenshuo Zhang and Ruoxuan Xiong and Gene Cooperman and Hongyang R. Zhang},
  title = {{Long-Context Demonstration Selection Using State Space Models}},
  year = {2026},
  eprint = {2609.17888},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2609.17888},
}
Figure