Linear-Time Demonstration Selection for In-Context Learning via Gradient Estimation

Ziniu Zhang, Zhenshuo Zhang, Dongyue Li, Lu Wang, Jennifer G. Dy, Hongyang R. Zhang

TL;DR

Selecting the perfect few-shot examples for In-Context Learning (ICL) usually requires a painful trade-off between speed (simple similarity searches) and accuracy (expensive brute-force evaluation). This paper introduces a gradient-based estimation method that uses first-order Taylor expansions to predict model performance for any subset of demonstrations in linear time. The result is a selection process that is up to 37.7x faster than full-inference methods while outperforming embedding-based baselines by 11%.

What Problem Does This Paper Address?

Large Language Models (LLMs) are notoriously sensitive to the "demonstrations" (examples) provided in their prompts. Choosing a different set of examples can swing a model's performance from stellar to mediocre.

Currently, researchers use two main approaches to pick these examples:

  1. Similarity-based (Top-k): Pick examples whose embeddings are similar to the query. This is fast but "blind"—it ignores the labels of the examples and how different examples might interact with each other.
  2. Inference-based (Forward Selection/Ensembling): Actually run the LLM on various subsets of examples to see which ones work best. This is accurate but computationally ruinous, requiring hundreds or thousands of forward passes.

The authors tackle the "efficiency-accuracy" gap: How can we select the best subset of demonstrations without actually running the model a thousand times?

Methods

The core innovation is ICL-GRADEX (In-Context Learning via Gradient Estimation). Instead of running a full forward pass for every possible subset of demonstrations, the authors use a first-order Taylor approximation in the input embedding space.

  1. The Anchor: They pick one "anchor" prompt ($S_0$) and compute the model's output and the gradient of that output with respect to the input embeddings.
  2. The Approximation: To estimate the output for any other subset ($S$), they take the anchor's output and add the dot product of the gradient and the difference in embeddings: $$f(S) \approx f(S_0) + \nabla f(S_0) \cdot (\text{Embed}(S) - \text{Embed}(S_0))$$
  3. Dimensionality Reduction: Because gradients for LLMs are massive, they use the Johnson-Lindenstrauss lemma (random projection) to squash the gradient vectors into a lower-dimensional space (e.g., 400 dimensions) while preserving their geometric relationships.
  4. Selection Algorithms: They apply this estimation to three selection strategies:
  5. ICL-GRADRE: A random ensemble approach that averages estimated scores across many random subsets.
  6. ICL-GRADFS: An accelerated version of greedy forward selection.
  7. ICL-GRADCE: An accelerated cross-entropy loss-based selection.

Datasets

The authors evaluated their approach across six diverse datasets:

  • Sentiment Classification: Poem Sentiment, SST-2 (movie reviews), and CR (customer reviews).
  • Reasoning Tasks: Edge Existence (GraphQA), Modular Addition, and Coin Flip.
  • Additional Benchmarks: StrategyQA, Snarks, and Sports Understanding (from BIG-Bench Hard).

They tested these on a wide range of LLMs, including Llama (1B to 13B), DeepSeek-7B, Qwen (7B to 8B), and CodeLlama-34B.

Key Insights and Ideas

  • The "Linear-Time" Magic: Because the gradients only need to be computed once per training example, the complexity of selecting a subset becomes linear relative to the size of the training set.
  • Surprising Accuracy: The first-order approximation isn't just "close enough"—it yields less than 1% error compared to full model inference across seven different LLMs.
  • Scaling Favorability: Interestingly, larger models (like CodeLlama-34B) actually showed lower approximation errors than smaller ones, suggesting this technique becomes more reliable as models grow.
  • Label Awareness: Unlike similarity-based methods, gradient estimation "sees" how the model reacts to specific labels and reasoning chains, allowing it to identify high-influence examples that embeddings alone would miss.

Key Results

  • Massive Speedups: On the Coin-Flip dataset with a DeepSeek-7B model, ICL-GRADFS achieved a 37.1x reduction in computation time compared to standard forward selection.
  • Performance Gains: ICL-GRADRE improved the test $F_1$ score by an average of 11% over the strongest embedding-based baselines.
  • Context Efficiency: In long-context settings, the method matched the performance of standard baselines while using 30x less context length (e.g., matching a 9000-token prompt with just 600 tokens).
  • Low Overhead: The memory cost of storing the projected gradients is minimal, typically adding less than 30% to the standard inference memory footprint.

Limitations and Future Work

  • OOD Robustness: The authors acknowledge that while the method works great within the training distribution, its performance in out-of-distribution (OOD) scenarios remains an open question.
  • Anchor Sensitivity: The choice of the initial "anchor" prompt matters. While random selection works, more principled anchor selection strategies could further reduce error.
  • Prompt Engineering: The current work focuses on selecting examples, but the authors suggest the framework could be extended to optimizing the wording of the instructions themselves (prompt engineering).
  • Fixed Weights: The method is designed for ICL where weights are frozen; it does not currently address scenarios involving parameter-efficient fine-tuning (PEFT).

Summary updated

BibTeX
@inproceedings{zhang2025linear,
  author = {Ziniu Zhang and Zhenshuo Zhang and Dongyue Li and Lu Wang and Jennifer G. Dy and Hongyang R. Zhang},
  title = {{Linear-Time Demonstration Selection for In-Context Learning via Gradient Estimation}},
  booktitle = {Conference on Empirical Methods in Natural Language Processing},
  year = {2025},
  url = {https://openreview.net/forum?id=KakpAUSCo2},
}
Figure