Selecting Demonstrations for Many-Shot In-Context Learning via Gradient Matching

Jianfei Zhang, Bei Li, Jun Bai, Rumei Li, Yanmeng Wang, Chenghua Lin, Wenge Rong · DOI

Introduction

In-Context Learning (ICL) has revolutionized how we interact with Large Language Models (LLMs), allowing them to adapt to new tasks through prompt examples rather than weight updates. As context windows expand to accommodate millions of tokens, "many-shot" ICL—utilizing hundreds or thousands of demonstrations—has emerged as a powerful paradigm. However, selecting the optimal set of demonstrations for these long prompts remains a significant challenge.

In traditional few-shot settings, instance-level retrieval (selecting examples similar to a specific query) is common. In the many-shot regime, this approach becomes computationally prohibitive ($O(n^2)$ complexity) and prevents the use of prefix-caching, a critical optimization for reducing inference latency and cost. Consequently, most practitioners resort to random task-level selection. This paper introduces Curriculum Latent Gradient (CLG), a method to intelligently select a fixed, high-performing subset of demonstrations that represents the entire task, enabling both high performance and efficient prefix-caching.

Methodology: Curriculum Latent Gradient (CLG)

The core hypothesis of CLG is that the data requirements for ICL are fundamentally analogous to those of traditional fine-tuning. By identifying which examples most effectively "teach" a model during training, we can select the most informative demonstrations for the prompt.

The CLG pipeline consists of three primary stages:

  1. Latent Concept Learning: A small "proxy" model (e.g., Llama-3-8B) is trained on the target task using prefix-tuning. This allows the model to learn the task's underlying structure within its latent space.
  2. Gradient Tracking: During training, the system records the gradients each individual example contributes to the prefix embeddings across multiple epochs. This creates a "curriculum learning trace" for every data point.
  3. Gradient Matching: Using a greedy search and local optimization algorithm, CLG selects a subset of $n$ demonstrations whose average gradient trajectory most closely mimics the average gradient of the entire training dataset.

This approach ensures that the selected subset captures the essential learning dynamics of the full dataset, effectively compressing the task's knowledge into a fixed-length prompt.

Experimental Setup

The authors evaluated CLG across nine datasets covering five distinct NLP domains:

  • Classification: SST-5, MNLI, CMSQA, and HellaSwag.
  • Generation and Semantic Parsing: GeoQuery, NL2Bash, Break, MTOP, and SMCalFlow.

The evaluation tested the transferability of demonstrations selected by small proxy models to much larger open-weights models (Llama-3-70B, Qwen-2.5-72B) and closed-source APIs (GPT-4o-mini, DeepSeek-V3, GLM-4).

Key Results and Insights

Performance Gains

CLG consistently outperformed random selection. In 128-shot settings, it achieved an average accuracy boost of 4% on Llama3-70B and Qwen2.5-72B. Even when transferred to black-box commercial APIs, the CLG-selected demonstrations maintained a ~2% lead over random baselines.

Cross-Model Transferability

A significant finding is that gradients from a cheap, small model (3B or 8B parameters) are highly predictive of performance on massive models. This suggests that the "informativeness" of an example is somewhat model-agnostic, allowing for cost-effective demonstration selection.

Inherent Diversity and Scaling

The gradient matching process naturally selects a diverse set of examples. For instance, the label distribution in the CLG subset closely matches the true distribution of the test set without explicit balancing. Furthermore, while classification tasks often saturate early, complex generation tasks (like semantic parsing) showed continued performance improvements as the number of shots scaled up to 1024.

Hybrid ICL

The researchers also explored a "Hybrid ICL" approach, combining a fixed 128-shot CLG prompt with 4 dynamically retrieved instance-level examples. This configuration yielded the highest overall performance, balancing the efficiency of prefix-caching with the relevance of query-specific examples.

Limitations and Future Considerations

While CLG offers a robust framework for demonstration selection, several areas remain for future exploration:

  • Ordering: CLG identifies which examples to include but does not optimize their sequence, which is known to impact ICL performance.
  • Bias Preservation: Because CLG mimics the full training set, it may inadvertently replicate biases present in the source data.
  • Security: The authors warn that optimized many-shot prompts could potentially be used for "many-shot jailbreaking" of aligned models.

Conclusion

Curriculum Latent Gradient (CLG) provides a scalable, efficient solution for the demonstration selection problem in many-shot ICL. By bridging the gap between fine-tuning dynamics and in-context learning, CLG enables practitioners to maximize the potential of long-context LLMs without the overhead of per-query retrieval.

Summary updated

BibTeX
@inproceedings{zhang2025selecting,
  author = {Jianfei Zhang and Bei Li and Jun Bai and Rumei Li and Yanmeng Wang and Chenghua Lin and Wenge Rong},
  title = {{Selecting Demonstrations for Many-Shot In-Context Learning via Gradient Matching}},
  booktitle = {Annual Meeting of the Association for Computational Linguistics},
  year = {2025},
}
Figure