PR-MaGIC: Prompt Refinement Via Mask Decoder Gradient Flow For In-Context Segmentation

Minjae Lee, Sungwoo Hur, Soojin Hwang, Won Hwa Kim

TL;DR

PR-MaGIC is a training-free, test-time optimization framework that automatically fixes bad or misaligned prompts in few-shot image segmentation. By leveraging mathematical gradient flow directly from the Segment Anything Model’s (SAM) pre-trained mask decoder, it iteratively refines query prompts to significantly boost segmentation accuracy without requiring any fine-tuning or architectural changes.

What Problem Does This Paper Address?

Visual Foundation Models like SAM have revolutionized image segmentation, but they typically require manual prompts (like points or bounding boxes) to know what to segment. To automate this, "in-context" or few-shot segmentation methods try to automatically generate prompts for a query image by semantically matching it with a labeled support image.

However, real-world images are messy. Differences in viewpoint, color, and shape between the support and query images often lead to noisy, ambiguous, or flat-out incorrect auto-prompts. This confuses SAM's decoder, resulting in incomplete masks or fragmented boundaries. Existing solutions try to solve this by fine-tuning the model, which requires extra training data, parameters, and manual effort. PR-MaGIC aims to solve this entirely at inference time without changing a single weight of the model.

Methods

PR-MaGIC introduces a test-time optimization loop that treats prompt refinement as a gradient flow problem in Wasserstein space. The framework operates in three main steps:

  1. Image Embedding: Support and query images are passed through a frozen vision encoder to extract initial embeddings.
  2. Prompt Refinement via Gradient Flow: Instead of training a separate discriminator to judge mask quality, the authors cleverly use SAM’s own mask decoder as a proxy. By treating the decoder's logit outputs as a probability density ratio, they derive an entropy-regularized Kullback-Leibler (KL) gradient flow. This gradient flow iteratively updates the query image embeddings to maximize mask quality, and new prompts are resampled from the updated similarity maps at each step $t$.
  3. Segmentation Mask Selection (Top-1 Similarity): Optimization trajectories aren't always perfectly monotonic. To ensure robustness, PR-MaGIC generates candidate masks across $T$ iterations. It then uses a masked average pooling strategy to select the final mask that exhibits the highest cosine similarity to the support image's target features.

A key architectural detail is that the refined embeddings are only used to resample the prompt points. The actual mask generation still uses the stable, original image embeddings, preventing representation collapse or instability.

Overview of the PR-MaGIC framework showing the embedding, gradient flow refinement, and mask selection steps.

Datasets

The authors evaluated PR-MaGIC across six standard benchmarks spanning two distinct granularities:

  • Semantic Segmentation (Object-level):
  • FSS-1000 (Few-Shot Segmentation dataset)
  • COCO-$20^i$
  • LVIS-$92^i$
  • Part Segmentation (Fine-grained/Component-level):
  • PASCAL-Part
  • PACO-Part
  • DIS5K (Dichotomous Image Segmentation)

Key Insights and Ideas

  • The Decoder as a Teacher: The core "aha moment" is realizing that SAM’s mask decoder already contains rich, latent semantic knowledge from its massive pre-training. Instead of treating it as a passive feed-forward component, PR-MaGIC backpropagates through it to guide the input embeddings.
  • Decoupled Prompting: Directly altering image features at test-time can ruin global context. By isolating the gradient updates strictly to the prompt generation space while keeping the base image representation frozen for final decoding, the method balances adaptability with robustness.
  • The Fragility of the Proximity Assumption: Theoretically, gradient flow guarantees exponential convergence if you start close to the optimal solution. However, the authors show that in practice, real-world visual gaps break this assumption, causing non-monotonic performance dips over iterations. The introduction of the Top-1 similarity selection acts as a vital practical safeguard against this instability.

Key Results

PR-MaGIC was integrated as a plug-and-play module onto two prominent auto-prompting baselines: PerSAM-F and Matcher.

Quantitative Improvements

PR-MaGIC consistently outperformed the baselines across all datasets:

  • Object-Level: When applied to PerSAM-F, it boosted mean Intersection over Union (mIoU) by +8.8%p on FSS-1000, +2.2%p on COCO-$20^i$, and +2.1%p on LVIS-$92^i$.
  • Part-Level: For Matcher (1-shot), it yielded substantial gains on fine-grained tasks, improving mIoU by +3.8%p on PACO-Part and a massive +8.4%p on the challenging DIS5K dataset.

Qualitative Improvements

Visually, PR-MaGIC successfully prunes false-positive prompt points located on the background or unrelated objects. This leads to much cleaner boundaries, fills in small holes, and recovers fine-grained details (like bicycle wheels or animal limbs) that baseline methods completely missed.

Figure 2. Example of prompts (green dots) and segmentation results (red masks). (a) Support Image (elephant), (b) and (c) Misaligned prompts and segmentation results from PerSAM-F and Matcher, (d) Result from Matcher refined by PR-MaGIC, (e) Ground Truth.

Limitations and Future Work

While highly effective, PR-MaGIC is bounded by the initial semantic relationship between the support and query images. If the visual domain gap is excessively large (e.g., highly disparate viewpoints or extreme intra-class variations), the initial auto-prompts might fall completely outside the decoder's optimal neighborhood, causing the gradient flow to struggle or diverge.

Additionally, if the support image mask itself is ambiguous or covers a generic region, the refined prompts can underperform. Future work could explore more sophisticated similarity metrics or adaptive step-size schedules to better bridge extreme semantic gaps.

Summary updated

BibTeX
@inproceedings{lee2026pr,
  author = {Minjae Lee and Sungwoo Hur and Soojin Hwang and Won Hwa Kim},
  title = {{PR-MaGIC: Prompt Refinement Via Mask Decoder Gradient Flow For In-Context Segmentation}},
  booktitle = {IEEE/CVF Conference on Computer Vision and Pattern Recognition},
  year = {2026},
  url = {https://openreview.net/forum?id=XqyBPoHAkX},
}
Figure