In-Context Clustering with Large Language Models

Ying Wang, Mengye Ren, Andrew Gordon Wilson

TL;DR

The paper introduces In-Context Clustering (ICC), a novel framework that repurposes Large Language Models (LLMs) to perform unsupervised clustering on numeric and image data simply through prompting. By leveraging the model's internal attention mechanism rather than rigid, predefined distance metrics, ICC achieves highly flexible, context-dependent data grouping and enables text-conditioned clustering (e.g., switching from clustering images by "species" to "color" on the fly).

What Problem Does This Paper Address?

Traditional clustering algorithms like $k$-means rely heavily on predefined similarity metrics (such as Euclidean distance), which inherently assume specific underlying data distributions (like spherical Gaussian clusters). Consequently, they struggle with high-dimensional, semantically intricate data or heavy-tailed distributions where the definition of "similarity" changes based on context.

While recent methods have tried using LLMs for text clustering, extending this capability to non-textual modalities (like numbers and images) has remained difficult. Existing multimodal approaches often convert images into text captions before clustering, which introduces severe information loss and fails if the captioning model misses subtle or domain-specific nuances.

Methods

The authors propose In-Context Clustering (ICC), which shifts in-context learning from a supervised task to an unsupervised one. Instead of providing input-output pairs, the prompt contains a natural language instruction specifying the clustering criteria followed by a sequence of unlabeled inputs. The LLM then autoregressively outputs the cluster labels.

Figure 1: In-Context Clustering (ICC). LLMs can flexibly handle diverse modalities and perform text- conditioned clustering. We show the zero-shot clustering capability in pretrained LLMs and further strengthen it through finetuning.

Key components of their approach include:

  1. Zero-Shot Prompting: Pretrained LLMs are fed text-encoded numeric data to evaluate their innate clustering capabilities.
  2. Attention Matrix Spectral Clustering: The authors discovered that the LLM's intermediate transformer layers naturally form distinct block structures corresponding to data clusters. By extracting and preprocessing these input-to-input attention matrices, they can apply classical spectral clustering directly to the model's internal representations.
  3. LoRA Fine-Tuning: To boost performance—especially for smaller open-source models—they fine-tune the models on generated clustering episodes using Low-Rank Adaptation (LoRA) and standard Next Token Prediction (NTP) loss.
  4. Multimodal Average Pooling: For image clustering, they use a pretrained vision encoder (SigLIP). To prevent context-length explosion from high-resolution patch tokens, they introduce an average pooling layer after the projection matrix to compress image features into a compact sequence of tokens.

Datasets

The framework was evaluated across multiple data modalities:

  • Numeric Data: Synthetic datasets sampled from $t$-distributions with varying degrees of freedom ($df$) to simulate heavy-tailed behavior, as well as skewed lognormal distributions.
  • Image Data: 18,000 classes from ImageNet21k were used for fine-tuning, while 384 classes from ImageNet-with-Attributes were reserved for testing.
  • Out-of-Domain Evaluation: To test generalization, the authors evaluated their model on Plant Disease (leaf images), EuroSAT (satellite imagery), and the Stanford 40 Action dataset.

Key Insights and Ideas

  • Emergence of Clusters in Attention: One of the most fascinating findings is that pretrained LLMs implicitly learn data similarity functions during text pretraining. Visualizing the self-attention matrices reveals salient block-diagonal cluster patterns in the intermediate layers long before the final output token is generated.
  • Spectral Clustering Beats Generation (Zero-Shot): In zero-shot settings, performing spectral clustering directly on these internal attention matrices often yields substantially higher accuracy than relying on the LLM's generated text outputs.
  • Dynamic Text-Conditioning: Unlike classical algorithms that require feature re-engineering to change clustering behavior, ICC can completely alter its grouping strategy (e.g., shifting from clustering by an object's shape to its texture) solely by modifying the natural language prompt.

Key Results

Numeric Clustering

On highly heavy-tailed data ($df = 1$), traditional $k$-means fails due to its Gaussian assumptions, scoring an accuracy of 67.95%. In contrast, a fine-tuned Llama-3.1-8B-Instruct model using ICC achieves an impressive 90.66%, even outperforming proprietary models like GPT-4o (77.75%).

Table 1: Effect of Finetuning on t-Distributed Data with Different Degrees of Freedom. Input dim = 3 and number of clusters c = 3. We report average accuracy (%) and one standard error.

Image Clustering

When tested on ImageNet data, ICC significantly outperformed caption-based LLM clustering baselines (like IC|TC), which suffer from information bottlenecks. On out-of-domain datasets like EuroSAT, caption-based methods collapsed (72.97%) due to a lack of domain-specific language descriptions, whereas ICC maintained robust performance.

Text-Conditioned Clustering

ICC demonstrated strong capabilities in dynamically shifting criteria. On the Stanford 40 Action dataset, when prompted to cluster by "action," "mood," or "location," the fine-tuned ICC models consistently outperformed unconditional $k$-means and caption-based alternatives across almost all categories.

Limitations and Future Work

Despite its flexibility, ICC faces a few notable constraints:

  • Context Length & Scalability: Because all data points must reside within the prompt context, ICC is currently limited to small-to-medium datasets (e.g., dozens of items) and cannot scale to millions of points without hitting context window or computational limits.
  • Inductive Biases: The image-finetuned models showed lower performance when clustering based on abstract human traits like "mood" or "location." The authors attribute this to ImageNet's heavy bias toward prominent foreground objects.

Future work aims to integrate token pruning and dynamic context selection to scale ICC to larger datasets, alongside developing rigorous theoretical frameworks to better understand how these cluster structures emerge within self-attention dynamics.

Summary updated

BibTeX
@misc{wang2025context,
  author = {Ying Wang and Mengye Ren and Andrew Gordon Wilson},
  title = {{In-Context Clustering with Large Language Models}},
  year = {2025},
  eprint = {2510.08466},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2510.08466},
}
Figure