Stable Diffusion Models are Secretly Good at Visual In-Context Learning

Trevine Oorloff, Vishwanath Sindagi, Wele Gedara Chaminda Bandara, Ali Shafahi, Amin Ghiasi, Charan Prakash, Reza Ardekani

TL;DR

This paper demonstrates that off-the-shelf, pre-trained Stable Diffusion models can perform Visual In-Context Learning (V-ICL) across diverse computer vision tasks without any fine-tuning or additional training. By introducing a novel in-place attention re-computation mechanism ($Q_{query}, K_{prompt}, V_{groundtruth}$) and a latent-space prompt ensembling technique, the authors unlock true training-free, emergent in-context learning for vision foundation models.

What Problem Does This Paper Address?

In-context learning (ICL)—the ability of a model to infer a task from a few exemplar inputs and targets (prompts) and apply it to a new input (query)—is a celebrated emergent property of Large Language Models (LLMs). However, translating this to computer vision has proven difficult.

Existing Visual ICL (V-ICL) methods typically fall into two categories: those trained on uncurated datasets via masked image inpainting (e.g., Visual Prompting, IMProv) and those fine-tuned on curated, task-specific datasets (e.g., Painter, SegGPT). The authors argue that both approaches violate the core spirit of ICL: they require expensive weight updates and struggle to generalize to truly out-of-domain tasks. Furthermore, existing inpainting-based methods often fail to fully leverage the prompt context, sometimes failing even to reconstruct the provided prompt example itself.

Figure 1. Existing V-ICL methods require specialized training of foundation models on curated/uncurated data before using them for novel downstream tasks. In contrast, our approach repurposes an off-the-shelf Stable Diffusion model without any additional training or data.

Methods

The authors introduce SD-VICL (Stable Diffusion-based Visual In-Context Learning), an inference-only pipeline that repurposes a standard Stable Diffusion v1.5 model.

The core technical innovation is In-place Attention Re-computation within the self-attention layers of the denoising U-Net:

  1. Inversion: The prompt image ($A$), prompt ground truth ($B$), and query image ($C$) are mapped into Stable Diffusion's noise space using DDPM inversion.
  2. Attention Routing: During parallel denoising, the self-attention mechanism for the prediction path ($D$, initialized with the query's noise) is modified. Instead of standard self-attention, the layer computes attention using: $$\Delta\phi_D^{(t)} = \text{softmax}\left(\frac{Q_C^{(t)} \cdot K_A^{(t)T}}{\tau \cdot \sqrt{d}}\right) \cdot V_B^{(t)}$$ By routing the Query vector from the query image ($Q_C$), the Key vector from the prompt image ($K_A$), and the Value vector from the prompt ground truth ($V_B$), the model is forced to explicitly map the semantic correspondences between the query and the prompt, and project the output directly into the target domain.

  3. Refinement: Mechanisms like attention map contrasting, swap-guidance, and Adaptive Instance Normalization (AdaIN) are adapted to mitigate the domain gap caused by mixing features from three distinct images.

  4. Implicitly-Weighted Prompt Ensembling (IWPE): To leverage multiple exemplar prompts without losing resolution (a common issue when stitching images in the pixel space), the authors concatenate the Key ($K$) and Value ($V$) vectors of multiple prompts in the latent space. This allows the attention mechanism to dynamically and implicitly weight the most relevant prompt patches for each query patch.
The SD-VICL pipeline featuring DDPM inversion and in-place attention re-computation.

Datasets

The approach was evaluated across six distinct downstream vision tasks using the following datasets:

  • Foreground Segmentation & Single Object Detection: Pascal-5i dataset (20 object classes split into 4 subsets).
  • Semantic Segmentation: Cityscapes (19 classes) and COCOStuff (27 mid-level classes).
  • Keypoint Detection: DeepFashion (human pose estimation mapping 17 keypoints as heatmaps).
  • Edge Detection: NYUDv2 validation set (using soft edge maps from HED as pseudo-groundtruth).
  • Colorization: ImageNet validation set (a random subset of 1,000 images).

Key Insights and Ideas

  • Generative Models are Latent Matchmakers: Off-the-shelf text-to-image diffusion models inherently possess deep structural and semantic cross-image awareness. We don't need to train them to understand "tasks"; we just need to reroute their internal attention mechanisms to act as a bridge between a query and an exemplar.
  • Pixel Stitching Destroys Resolution: Previous methods stitched multiple prompt examples into a single grid-like canvas, reducing the effective resolution per image. Ensembling in the latent space preserves full image resolution.
  • Dynamic Weighting Beats Uniform Averaging: Unlike prior feature-space ensembling methods (like SegGPT) that uniformly average features, IWPE lets the query "choose" which prompt is most relevant on a per-patch basis via the softmax attention matrix. This is crucial for complex, multi-class tasks like semantic segmentation.

Key Results

SD-VICL consistently outperformed existing training-free and uncurated baselines across all six tasks:

  • Foreground Segmentation: On Pascal-5i, a single-prompt achieved a 43.92% mIoU, outperforming Visual Prompting (35.04%) and IMProv (40.69%). Switching to 5 prompts via IWPE boosted the score to 55.49% mIoU.
  • Keypoint Detection: On DeepFashion, the method achieved a 6× reduction in MSE and a massive jump in the Percentage of Correct Keypoints (77.19% PCK vs. IMProv's 2.81%).
  • Edge Detection & Colorization: Drastically reduced LPIPS and MSE/FID scores compared to baselines, demonstrating a superior ability to preserve fine structural details.
  • Vs. Task-Specific Models: SD-VICL even outperformed models explicitly engineered or optimized for single tasks, such as DAS for semantic segmentation (+10.3% mIoU) and StableKeypoints for keypoint detection (+12.2% PCK).
Qualitative comparison showing SD-VICL's superior performance across six vision tasks.

Limitations and Future Work

  • Inference Latency: Because the method relies on iterative diffusion denoising (70 steps in the main experiments) across multiple parallel image paths, the computational cost and inference time are high.
  • Prompt Sensitivity: Like all ICL methods, performance degrades if the retrieved prompt examples are highly noisy, inaccurate, or ambiguous.
  • Future Directions: The authors suggest integrating fast-forward diffusion distillation techniques (like DMD or InstaFlow) to achieve up to 100× speedups, as well as extending this training-free framework to video generative models for temporal in-context learning.

Summary updated

BibTeX
@misc{oorloff2025stable,
  author = {Trevine Oorloff and Vishwanath Sindagi and Wele Gedara Chaminda Bandara and Ali Shafahi and Amin Ghiasi and Charan Prakash and Reza Ardekani},
  title = {{Stable Diffusion Models are Secretly Good at Visual In-Context Learning}},
  year = {2025},
  eprint = {2508.09949},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2508.09949},
}
Figure