Delving into Out-of-Distribution Detection with Vision-Language Representations
Abstract
Recognizing out-of-distribution (OOD) samples is critical for machine learning systems deployed in the open world.
The vast majority of OOD detection methods are driven by a single modality ( e.g. , either vision or language), leaving the rich information in multi-modal representations untapped.
Inspired by the recent success of vision-language pre-training, this paper enriches the landscape of OOD detection from a single-modal to a multi-modal regime.
Particularly, we propose Maximum
Concept Matching (MCM), a simple yet effective zero-shot OOD detection method based on aligning visual features with textual concepts.
We contribute in-depth analysis and theoretical insights to understand the effectiveness of MCM.
Extensive experiments demonstrate that MCM achieves superior performance on a wide variety of real-world tasks.
MCM with vision-language features outperforms a common baseline with pure visual features on a hard OOD task with semantically similar classes by 56.60% (FPR95).
Code is available at https://github.com/ deeplearning-wisc/MCM .
Introduction
Out-of-distribution (OOD) detection is critical for deploying machine learning models in the wild, where samples from novel classes can naturally emerge and should be flagged for caution.
Despite increasing attention, the vast majority of OOD detection methods are driven by single-modal learning [22, 24, 29, 61, 80, 83, 85, 88].
For example, labels are typically encoded as one-hot vectors in image classification, leaving the semantic information encapsulated in texts largely unexploited.
OOD detection relying on pure visual information can inherit the limitations, e g. , when an OOD input may be visually similar to in-distribution (ID) data yet semantically different from any ID class.
In this paper, we delve into a new landscape for OOD detection, departing from the classic singlemodal toward a multi-modal regime.
While the motivation is appealing, a core challenge remains: how to effectively utilize joint vision-language features for OOD detection?
In the visual domain, existing methods typically require good feature representations [59, 65], and a distance metric under which
OOD data points are relatively far away from the in-distribution (ID) data [37, 64].
These approaches, however, do not directly translate into the multi-modal regime.
On the representation learning side, recent vision-language pre-training schemes such as CLIP [53] and ALIGN [28] have emerged as promising alternatives for visual representation learning.
The main idea is to align an image with its corresponding textual description in the feature space.
While the resulting representations are powerful, OOD detection based on such aligned multi-modal features is still in its infancy.
We bridge the gap by exploring a distance-based OOD detection approach, leveraging the joint vision-language representations.
Our method capitalizes on the compatibility between visual features and textual features.
By defining the textual features as the “concept prototypes” for each ID class, we characterize OOD uncertainty by the distance from the visual feature to the closest ID prototype.
[Figure]
“This is a photo of a ______”
[Figure] [Figure]
[Figure]
That is, images closer to one of the textual embeddings of ID classes are more likely to be ID and vice versa.
By a proper scaling of the distance, our proposed Maximum Concept Matching ( MCM ) score achieves strong ID-OOD separability (see Figure 1).
MCM stands in contrast with the previous distance-based approaches, such as Mahalanobis [37], which defines class prototypes based on pure visual embeddings.
Indeed, we show later in Section 5 that MCM (with multi-modal vision-language features) is far more competitive than Mahalanobis (with single-modal visual features).
Moreover, while prior works of CLIP-based OOD detection [14, 16] rely on a set of candidate OOD labels,
MCM is OOD-agnostic and alleviates the need for any prior information about test inputs.
Our work also advances the field by showcasing the promise of zero-shot OOD detection, which offers strong performance and generality without training on the ID samples.
In particular, classic
OOD detection methods often require training from scratch [8, 23] or fine-tuning [16, 27] on a given
ID dataset.
In this setting, a classifier and its companion OOD detector are good at only one task.
Every new task (ID dataset) requires additional training and brings additional computation and storage costs.
In contrast, we show for the first time that: (1) MCM achieves superior performance across a wide variety of real-world tasks—with just one single pre-trained model .
This is encouraging given that there is no training or any OOD information involved.
On the challenging ImageNet-1k benchmark, MCM’s zero-shot OOD detection performance favorably matches and even outperforms strong task-specific baselines fine-tuned on BiT [27] and ViT models [16].
(3) MCM remains robust against hard OOD inputs, including both semantically hard OODs [76] and spurious OODs [44].
We summarize our main contributions as follows:
We propose MCM, a simple yet effective OOD detection method based on aligned visionlanguage features.
MCM offers several compelling advantages over other OOD detection methods: generalizable (one model supports many tasks), OOD-agnostic (no information required from OOD data), training-free (no downstream fine-tuning required)
and scalable to large real-world tasks.
We conduct extensive experiments and show that MCM achieves superior performance on a wide range of real-world tasks.
On ImageNet-1k, MCM achieves an average AUROC of 91.78%, outperforming methods that require training.
Moreover, we show that MCM remains competitive under challenging hard OOD evaluation tasks.
We provide in-depth empirical and theoretical analysis, providing insights to understand the effectiveness of MCM.
We hope that this work will serve as a springboard for future works on OOD detection with multi-modal features.
Preliminaries
Contrastive vision-language pre
training.
Compared to visual representation learning models such as ViT [12], vision-language representation learning demonstrates superior performance on image classification tasks.
For instance, CLIP [53] adopts a self-supervised contrastive objective ( i.e ., InfoNCE loss [68]) to align an image with its corresponding textual description in the feature space.
Specifically, CLIP adopts a simple dual-stream architecture with one text encoder T : t → R d ( e.g ., Transformer [70]) and one image encoder I : x → R d ( e.g ., ViT [12]).
After pre-training on a dataset of 400 million text-image pairs, the joint vision-language embeddings of CLIP well associate objects in different modalities.
Despite the promise, existing CLIP-like models perform zero-shot classification in a closed-world setting.
That is, it will match an input into a fixed set of categories, even if it is irrelevant ( e.g ., a tree being predicted as a bird in Figure 1).
This motivates our work to leverage the multi-modal representation for OOD detection, which is largely unexplored.
Zero-shot OOD detection.
Given a pre-trained model, a classification task of interest is defined by a set of class labels/names Y in , which we refer to as the known (ID) classes.
Here ID classes are defined w.r.t.
the classification task of interest, instead of the classes used in pre-training.
Accordingly,
OOD is defined w.r.t.
the ID classes, not the data distribution during pre-training.
The goal of OOD detection is to (1) detect samples that do not belong to any of the known classes; (2) otherwise, assign test samples to one of the known classes.
Therefore, the OOD detector can be viewed as a “safeguard” for the classification model.
Formally, we denote the OOD detector as a binary function:
G ( x ; Y in , T , I ) :
X → { in , out } , where x ∈ X denotes a test image.
Our method is based on only the names of the given classes in Y in , and a pre-trained model.
Different from standard supervised learning, there is no training on the ID samples involved, hence zero-shot .
OOD Detection via Concept Matching
We illustrate our approach in Figure 1, which derives the OOD detector G ( · ) based on concept matching .
For a given task with label set Y in = { y 1 , y 2 , ..., y K } , we can construct a collection of concept vectors T ( t i ) , i ∈ { 1 , 2 , ..., K } , where t i is the text prompt “ this is a photo of a ⟨ y i ⟩ ” for a label
y i .
The concept vectors are represented by the embeddings of the text prompts.
For any test input image x ′ , we can calculate the label-wise matching score based on the cosine similarity between the image feature I ( x ′ ) and the concept vector T ( t i ) : s i ( x ′ ) =
[Equation]
Formally, we define the maximum concept matching ( MCM ) score as:
[Equation]
where τ is the temperature.
For ID data, it will be matched to one of the concept vectors (textual prototypes) with a high score; and vice versa.
Formally, our OOD detection function can be formulated as:
[Equation]
where by convention 1 represents the positive class (ID) and 0 indicates OOD.
λ is chosen so that a high fraction of ID data ( e.g ., 95%) is above the threshold.
For samples that are classified as ID, one can obtain the class prediction based on the closest concept: ˆ y = arg max i ∈
[ K ] s i .
Remark : (1) Our work differs from (and is complementary to) CLIP by focusing on OOD detection rather than (closed-world) zero-shot classification.
We show new theoretical insights next that softmax scaling plays a unique role in zero-shot OOD detection—improving the separability between ID and OOD data.
This role has not been studied rigorously for zero-shot OOD detection.
Readers familiar with CLIP may notice that MCM can be used for zero-shot classification in the closed world.
This also makes MCM practically convenient for dual goals: detect OOD samples and assign ID data to one of the known classes.
(2) Our method in principle is not limited to CLIP; it can be generally applicable for contrastive vision-language pre-training models that promote multi-modal feature alignment.
New insights on softmax scaling for zero-shot OOD detection.
We provide theoretical justifications that softmax scaling improves the separability between ID and OOD data for CLIP-based
OOD detection, which is contrary to models trained with cross-entropy (CE) loss.
In particular,
CLIP-like models are trained with a multi-modal contrastive loss, which maximizes the cosine similarity between an image and its textual description in the feature space.
The resulting cosine similarity scores display strong uniformity 1 across labels, as evidenced in Figure 2 (right).
Compared to OOD inputs, the gap between the maximum cosine similarity and the average is larger for ID inputs.
However, the gap can be small when the number of ID classes increases where ID samples occur with lower highest cosine similarity.
As a result, the highest cosine similarity for ID samples and OOD samples can be highly close ( c.f. Figure 2 (left)).
[Figure]
Motivated by these observations, MCM employs softmax as a post hoc mechanism to magnify the difference.
This is fundamentally different from the softmax score derived from a model trained with cross-entropy loss , which inherently maximizes the posterior p ( y | x ) for the ground-truth label, and minimizes the probability for other labels.
Unlike CLIPlike models, logit scores displaying uniformity would be heavily penalized by the CE loss.
As a result, the maximum logit score corresponding to the ground-truth label can already be significantly higher than other labels.
Applying softmax on the logit scores can exacerbate overconfident predictions, and reduce the separability between ID and OOD data [41].
Indeed, for a model trained with cross-entropy loss, a logit-based score such as Energy [43] is shown to be much more effective than the softmax score.
Interestingly, for CLIP-like models, the trend is the opposite—applying softmax helps sharpen the uniform-like inner product scores, and increases the separability between ID and OOD data.
To help readers better understand the insights, we first formalize our observations that OOD inputs trigger similar cosine similarities across ID concepts (Figure 2, right) as the following assumption:
Assumption 3.1.
Let z := 1 { y ∈ Y in } .
Q x denotes the out-of-distribution P x | z =
(marginal distribution of x conditioned on z = 0 ).
Assume ∃ δ > 0 such that
[Equation]
where ˆ y :=
argmax i ∈ [ K ] s i ( x ) and ˆ y 2 :=
argmax i ̸
=ˆ y,i ∈
[ K ] s i ( x ) denote the indices of the largest and second largest cosine similarities for an OOD input x .
Now we provide formal guarantees that using softmax can provably reduce the false positive rate (FPR) compared to that without softmax.
Theorem 3.1.
Given a task with ID label set Y in = { y 1 , y 2 , ..., y K } and a pre-trained CLIP-like model ( T , I ) .
If Q x satisfies Assumption 3.1, then there exists a constant T = λ (
[Equation]
such that for any temperature τ > T , we have
[Equation]
where FPR( τ, λ ) is the false positive rate based on softmax scaling with temperature τ and detection threshold λ ; FPR wo ( λ wo ) is the false positive rate without softmax scaling based on threshold λ wo . normalized features.
Moreover, as CLIP features lie on a high-dimensional space (512 for CLIP-B/16 and 768 for CLIP-L/14), uniformly distributed points in a high-dimensional sphere tend to be equidistant to each other [72].
Therefore, for OOD inputs, we observe approximately uniform cosine similarity with concept vectors.
This suggests that applying softmax scaling with a moderate temperature results in superior OOD detection performance compared to that without softmax scaling.
The proof is in Appendix A. Later in Section 5, we empirically verify on a real-world ImageNet dataset that our bound can indeed be satisfied in CLIP where the thresholds are chosen at 95% true positive rate.
What MCM offers: Beyond theoretical insights, we would like to highlight several compelling advantages of our zero-shot OOD detection approach, owing to the strong pre-trained CLIP model:
• Generalizable to
many tasks
: Traditional OOD detection methods are based
on
a task-specific model.
As a result, the OOD detector is not suitable for a realistic online scenario where the task changes from one to another.
In contrast, we will show
in Section
that MCM can perform a wide variety of OOD detection tasks, with just one single model.
For a new task
only the names of the task’s visual concepts Y in are required.
• OOD-agnostic : Our method does not rely on any OOD information, and thus suits many realworld scenarios where one cannot anticipate what the unknowns would be ahead of time.
This also mitigates the shortcoming of a recent approach [16], which assumes that a set of unseen labels are given as some weak information about OOD data.
• Training-free : MCM enables OOD detection in a completely zero-shot setting.
This stands in contrast to the vast majority of OOD detection literature, which often requires training from scratch or fine-tuning to achieve competitive performance.
• Scalable : The contrastive vision-language pre-training paradigm makes MCM scalable to a large number of class labels and realistic high-resolution images.
We now proceed to the experimental results, demonstrating these advantages on real-world tasks.
A Comprehensive Analysis of MCM 4.1 Datasets and Implementation Details
Datasets.
Most previous works on OOD detection only focus on small-scale datasets with blurry images such as CIFAR [35] and TinyImageNet [36].
With pre-trained models such as CLIP, OOD detection can be extended to more realistic and complex datasets.
In this work, we scale up evaluations in terms of (1) image resolution, (2) dataset variety, and (3) number of classes.
We consider the following ID datasets: C UB -200 [73], S TANFORD -C ARS [34], F OOD -101 [5], O XFORD -P ET [51] and variants of I MAGE N ET [10].
For OOD test datasets, we use the same ones in [27], including subsets of iNaturalist [69], S UN [77], P LACES [86], and T EXTURE [9].
For each OOD dataset, the categories are not overlapping with the ID dataset.
We also use subsets of ImageNet-1k for fine-grained analysis.
For example, we construct ImageNet-10 that mimics the class distribution of CIFAR-10 but with high-resolution images.
For hard OOD evaluation, we curate ImageNet-20, which consists of 20 classes semantically similar to ImageNet-10 ( e.g ., dog (ID) vs. wolf (OOD)).
Model.
In our experiments, we adopt CLIP [53] as the target pre-trained model, which is one of the most popular and publicly available vision-language models.
Note that our method is not limited to
CLIP; it can generally be applicable for contrastive vision-language pre-training models that promote multi-modal feature alignment.
Specifically, we mainly use CLIP-B/16, which consists of a ViT-B/
Transformer as the image encoder and a masked self-attention Transformer [70] as the text encoder.
To indicate the input patch size in ViT models, we append “/x” to model names.
We prepend -B, -L to indicate Base and Large versions of the corresponding architecture.
For instance, ViT-B/ implies the Base variant with an input patch resolution of 16 × 16 .
We also use CLIP-L/14 which is based on ViT-L/14 as a representative of large models.
Unless specified otherwise, the temperature τ is 1 for all experiments.
Details of the datasets, the experimental setup and hyperparameters are provided in Appendix B .
Metrics.
For evaluation, we use the following metrics: (1) the false positive rate (FPR95) of OOD samples when the true positive rate of in-distribution samples is at 95%, (2) the area under the receiver operating characteristic curve (AUROC), and (3) ID classification accuracy (ID ACC).
[Table] [Table]
4.2 Main Results
MCM supports a diverse collection of tasks while being zero-shot.
We first show that zero-shot
OOD detection with MCM is effective across a wide variety of tasks—with just one single pre-trained model .
To showcase the versatility of MCM, we consider the seven ID datasets here.
To the best of our knowledge, this is among the first attempts to showcase the efficacy under an expansive and diverse collection of ID datasets.
The zero-shot OOD detection performance is summarized in Table 1.
A salient observation is that MCM can achieve superior detection performance on many tasks.
For example, using S TANFORD -C ARS as ID, MCM yields an average FPR95 of 0.09 %.
Considering that there are no training samples or OOD information involved, these results are very encouraging.
It can be also seen from Table 1 that MCM is promising, especially when the number of samples per
ID class is limited in the training set.
For example, there are only around 40 samples per class for
Stanford-Cars, 100 for Oxford-Pet, and 30 for CUB-200.
The sample scarcity makes OOD detection methods that rely on fine-tuning difficult.
For example, after fine-tuning on Food-101, while the ID accuracy is increased from 86 .
3% to 92 .
5% ↑ , OOD detection based on MSP is on par with MCM ( 99 . 5% vs. 99 .
4% in AUROC).
MCM scales effectively to large datasets.
To examine the scalability of MCM, we compare it with recent competitive OOD detection methods [16, 27] on the ImageNet-1k dataset (ID) in Table 2.
We observe the following trends:
• Larger models lead to superior performance.
Compared with CLIP-B, MCM based on CLIP-L reduces FPR95 by 6 .
Zero-shot ID classification accuracy is also improved by 7% with the larger model, reaching 75 .
53% (see Appendix D).
This suggests that larger models are endowed with a better representation quality, which benefits both ID classification and OOD detection with MCM.
Our finding echos with the recent observations [71] that higher ID classification accuracy is correlated with stronger OOD detection performance.
• MOS [27] recently demonstrated competitive performance on ImageNet-1k, which requires model fine-tuning based on BiT [33].
In contrast, we show that MCM (CLIP-L) outperforms MOS by 1 .
67% in AUROC while being zero-shot (training-free).
• MCM shares a softmax scaling function with the classic (visual) confidence-based score MSP [21].
To implement MSP, we adopt the commonly used linear probe approach by fine-tuning a linear layer on frozen visual features of CLIP.
After fine-tuning, ID accuracy significantly improves, reaching 84 .
12% (CLIP-L).
Interestingly, the OOD detection performance of MSP is worse than
[Table]
MCM by 16 .
52% in FPR95.
Under the same model fine-tuned with linear probing, we observe that Energy score outperforms MSP, corroborating findings in [43].
We investigate more in Section 5.
Recently, Fort et al.
[16] explore small-scale OOD detection by fine-tuning the full ViT model.
When extended
to large-scale tasks, we find that
MCM
still yields superior performance under the same
image encoder configuration (ViT-B or ViT-L).
This further highlights the advantage of utilizing vision-language joint embeddings for large-scale visual OOD detection
MCM benefits hard OOD detection.
Going beyond, we investigate whether MCM is still effective for hard OOD inputs.
We consider the following two categories of hard OOD:
• Semantically hard OOD : OOD samples that are semantically similar to ID samples are particularly challenging for OOD detection algorithms [76].
To evaluate hard OOD detection tasks in realistic settings, here we consider ImageNet-10 (ID) vs. ImageNet-20 (OOD) and vice versa.
The pair consists of high-resolution images with semantically similar categories such as dog versus wolf.
As shown in Table 3, MCM outperforms Mahalanobis [37] by 56.50% in FPR95 for ImageNet- (ID) vs. ImageNet-20 (OOD) and 38.95% vice versa.
• Spurious OOD : Modern neural networks can exploit spurious correlations for predictions [3].
For example, in the Waterbirds dataset [57], there exist spurious correlations between the habitat ( e
g ., water) and bird types.
A recent work [44] proposes a new type of hard OOD named spurious OOD and shows that most OOD detection methods perform much worse for spurious OOD inputs compared to non-spurious inputs.
The spurious OOD inputs are created to share the same background ( i
e ., water) as ID data but have different object labels ( e
g ., a boat rather than a bird).
See Appendix C for illustrations.
The results are shown in Table 3.
It has been shown that CLIP representations are robust to distributional shifts [53].
Therefore, while prior works [44] show that spurious OOD inputs are challenging for methods based on ResNet [20], MCM and Mahalanobis scores based on pre-trained CLIP perform much better.
On the other hand, fine-tuning exposes the model to the training set containing spurious correlations.
As a result, MSP performs much worse than MCM ( 39 .
57% vs. 5 .
85% in FPR95).
[Figure]
MCM outperforms CLIP-based baselines.
Two recent works also use CLIP embeddings for OOD detection [14, 16].
However, fundamental limitations exist for both works.
Fort et al.
[16] assume that a candidate OOD label set Y C is known, and used (cid:80) y ∈Y C ˆ p ( y | x ) for OOD detection.
Here the predictive probability ˆ p ( y | x ) is obtained by normalizing the inner products over |Y in | + |Y C | classes.
While applying softmax converts any vector to probabilities, as we show in Section 3, the converted probabilities do not necessarily correspond to P ( OOD | x ) .
Moreover, obtaining such an
OOD label set is typically not feasible, which fundamentally limits its applicability.
A recent work [14] realizes this idea by training an extra text decoder on top of CLIP’s image encoder to generate candidate labels.
However, [14] cannot guarantee the generated labels are non-overlapping with the
ID labels.
We enhance the baseline with a stronger decoder and a filter module (see Appendix E.1).
As shown in Figure 3, MCM outperforms the enhanced baseline on all OOD datasets.
Moreover, MCM is much
[Figure]
D e n s i t y D e n s i t y
D e n s i t y D e n s i t y simpler to use—alleviating the need for an OOD label set or training an additional caption generator.
In contrast, the caption generator’s performance largely affects OOD detection.
Poor caption quality degenerates the OOD detection performance of candidate label-based methods.
Moreover, obtaining a reliable caption generator for any input image can significantly increase the computational overhead.
Discussion: A Closer Look at MCM
Empirical verification on the role of softmax.
In Section 3, we prove that softmax scaling on cosine similarity scores with a moderate τ improves the ID-OOD separability.
Here we empirically verify our theoretical results.
As shown in Figure 4, compared to directly using the maximum cosine similarity without softmax (leftmost figure), softmax scaling with a temperature τ = 1 significantly improves the performance by 30 . 8% in FPR95, and further increasing τ ( e.g ., τ = 10 ) leads to similar performance.
The results are based on ImageNet-100 (ID) versus SUN (OOD).
Now, we verify if our theoretical bound ( c.f. Theorem 3.1) is satisfied empirically as well in Figure 4.
From the leftmost figure, we can estimate λ wo ≈ 0 .
26 , δ ≈ 0 .
03 , and s ˆ y
≈ 0 .
By checking the third figure ( τ = 1 is the temperature value we use for most experiments), we approximate λ ≈ 0 . 011 .
As K = 100 , we plug in the values and obtain the lower bound T = λ (
[Equation]
[Equation] [Equation]
≈ 0 .
Since τ = 1 > 0 . 65 , by Theorem 3.1, applying softmax scaling with τ = 1 is provably superior to without softmax scaling for OOD detection.
[Figure]
Are vision-language features better than visual feature alone?
MCM can be interpreted as a distance-based approach—images that are closer to one of the K class prototypes are more likely to be ID and vice versa.
Here the class prototypes are defined based on a textual encoder.
Alternatively, one can define the class prototypes based on visual features.
For example, Mahalanobis [37] defines a class prototype as the average of visual embeddings for images belonging to the same class.
This raises the question of whether MCM (with multi-modal vision-language features) is better than Mahalanobis (with single-modal visual feature).
For a fair comparison, we use the same
ViT image encoder from CLIP-B. Both MCM and Mahalanobis extract visual features from the penultimate layer.
On ImageNet-1k, Mahalanobis displays a limited performance, with 73 .
87% AUROC averaged across four OOD test datasets ( 90.62% for MCM), as shown in Figure 5.
From a practical perspective, Mahalanobis requires computing the inverse covariance matrix, which can be both computationally expensive and inaccurate when the number of samples is scarce and the number of ID classes grows.
In contrast, MCM is easier to use and more robust.
MCM without softmax scaling.
In Section 3, we provide theoretical justifications on the necessity of softmax scaling for CLIP-like models.
To further verify our observations empirically, we show
OOD detection performance based on the maximum cosine similarity score S woMCM ( x ′ ; Y in , T , I )
= max i ∈
[ K ] s i ( x ′ ) .
The results are shown in Table 4.
For easy tasks such as Food-101 [34], StanfordCars [34], and Oxford-Pet [51] as ID, the performance of maximum cosine similarity score is similar
[Table]
to MCM (see Table 1 and Table 2).
However, for more challenging tasks such as ImageNet-20 and
ImageNet-1k, MCM significantly outperforms that without softmax scaling.
For example, the average
FPR95 is improved by 11.33% on ImageNet-20 and 22.02% on ImageNet-1k, which highlights the necessity of a proper scaling function for CLIP-based OOD detection.
MCM for ResNet-based CLIP models.
Our main results are based on the CLIP model with
ViT image encoder.
We additionally investigate the effectiveness of MCM on ResNet-based CLIP.
Specifically, we use RN50x4 (178.3M), which shares a similar number of parameters as CLIP-B/ (149.6M).
The results are shown in Table 5.
We can see that MCM still shows promising results with
ResNet-based CLIP models, and the performance is comparable between RN50x4 and CLIP-B/ ( 89 . 97 vs. 90 .
62 in AUROC).
[Table]
Effect of prompt ensembling.
We examine MCM’s performance with prompt ensembling.
For example, Radford et al.
[53] create 80 possible prompts according to the image modalities and nuances in ImageNet.
We experiment with the two prompt sets, one of size 80 as in [53] [Table] and our own set of 5 prompts.
Ensembles are obtained by averaging the textual features.
As expected, using ensembles increases the ID classification accuracy on ImageNet-1k (2% with CLIP-B and 3% with CLIP-L).
For OOD detection, the average FPR95 is reduced from 37.19% with the default prompt to 35.17% ↓ with an ensemble of five prompts shown in Table 6.
In addition, the detection performance with 5 prompts is slightly better than with 80 prompts.
Note that prompt ensembling does not increase the inference-time cost, as the textual embeddings (across many prompts) can be pre-calculated and averaged into a single embedding.
Related Works
OOD detection in computer vision.
For open-world multi-class classification, the goal of OOD detection is to derive a binary ID-OOD classifier along with a multi-class classification model for visual inputs.
A plethora of methods has been proposed for deep neural networks [81], including generative model-based methods [6, 17, 31, 47, 48, 50, 55, 60, 79], and discriminative-model based methods.
For the latter category, an OOD score can be derived based on the softmax output or logit layer [4, 11, 21, 24, 27, 41, 43, 62, 63], gradient information [26], or the feature embeddings [13, 37, 58, 59, 64, 65, 76] of a model.
Morteza et al.
[46] recently provided theoretical guarantees for existing
OOD detection scores.
Works insofar have mostly focused on OOD detection for a task-specific model using only visual information.
In contrast, we explore a novel paradigm of zero-shot OOD detection that incorporates rich textual information and can perform a wide variety of tasks.
OOD detection in natural language processing.
Distribution shifts can occur due to the change of topics and domains, unexpected user utterances, etc .
Challenging benchmarks [32] and characterization of distributional shifts [1] have been proposed in recent years.
Compared to early language models such as ConvNets and LSTMs, pre-trained language models are more robust to distribution shifts and more effective at identifying OOD instances [22, 52, 80].
Various algorithmic solutions are proposed to handle OOD detection, including outlier exposure [25], model ensembling [39], data augmentation [7, 83, 85], contrastive learning [29, 88], and an auxiliary module that incorporates domain labels [61].
Tan et al.
[66] also explore zero-shot OOD detection for text classification tasks.
However, prior works focus on pure natural language processing (NLP) settings, while we explore utilizing textual embeddings for zero-shot visual OOD detection.
Vision-language models.
Utilizing large-scale pre-trained vision-language models for multimodal downstream tasks has become an emerging paradigm with remarkable performance [19, 67].
In general, two types of architectures exist: single-stream models like VisualBERT [38] and ViLT [30] feed the concatenated text and visual features into a single transformer-based encoder; dual-stream models such as CLIP [53], ALIGN [28], and FILIP [82] use separate encoders for text and image and optimize with contrastive objectives to align semantically similar features in different modality.
In particular, CLIP enjoys popularity due to its simplicity and strong performance.
CLIP-like models inspire numerous follow-up works [40, 84, 87], which aim to improve data efficiency and better adaptation to downstream tasks.
This paper adopts CLIP as the target pre-trained model, but our approach can be generally applicable to contrastive models that promote vision-language alignment.
Multi-modal OOD detection.
Exploring textual information for visual OOD detection is a new area with limited existing works.
Fort et al.
[16] propose to feed the potential OOD labels to the textual encoder of CLIP [53].
Recently, Esmaeilpour et al.
[14] propose to train a label generator based on the visual encoder of CLIP and use the generated labels for OOD detection.
While both works rely on a set of candidate OOD labels, MCM is OOD-agnostic and alleviates the need for prior information on OOD.
Moreover, prior works [14, 53] only focus on small-scale inputs.
We largely expand the scope to a wide range of large-scale realistic datasets, and show new theoretical insights.
Conclusion
In this work, we delve into a new landscape for OOD detection, departing from the classic singlemodal toward a multi-modal regime.
By viewing the textual features as the “concept prototypes”, we explore a new OOD detection approach MCM, based on the joint vision-language representations.
Unlike the majority of OOD detection methods, MCM offers several compelling advantages: trainingfree, generalizable to many tasks, scalable to hundreds of classes, and does not require any prior information on OOD inputs.
Moreover, we provide theoretical guarantees on how softmax scaling provably improves zero-shot OOD detection.
We investigate the effectiveness of MCM on a wide range of large-scale realistic tasks, including several types of hard OOD datasets.
Lastly, we demonstrate the advantage of vision-language features over pure visual features for OOD detection.
We hope our work will inspire future research toward multi-modal OOD detection.
Acknowledgement
The authors wish to thank Junjie Hu, Ying Fan, Ruisu Zhang, Andrew Geng, and Soumya Suvra
Ghosal for the helpful discussions.
The work is supported by a Google-Initiated Research Grant, and gift funding from Adobe Research.
A Theoretical Justification: Softmax Scaling for Zero-Shot OOD Detection
In this section, we provide the proof for Theorem 3.1 in Section 3, which states the benefits of applying softmax scaling to inner products for OOD detection.
We begin with a review of notations.
Notations.
We denote the text encoder of a pre-trained CLIP-like model as T : t → R d and the image encoder I : x → R d .
For a given task with label set Y in = { y 1 , y 2 , ..., y K } , we construct a collection of concept vectors T ( t i ) .
For a given input x ′ , we denote the cosine similarity w.r.t.
concept vectors as s i ( x ′ ) =
I ( x ′ ) ·T ( t i ) ∥I ( x ′ ) ∥·∥T ( t i )
∥ ∀ i ∈
[ K ] , where | s i ( x ′ ) | ≤ B for all x ′ ∈ X . 2 .
We define the maximum concept matching (MCM) score as: S MCM ( x ′ ; Y in , T , I )
= max i ∈
[ K ]
[Equation]
We denote the maximum inner product without applying softmax scaling as S woMCM ( x ′ ; Y in , T , I )
= max i ∈
[ K ] s i ( x ′ ) .
By convention, the OOD detection functions are given by:
[Equation]
Remarks: By convention, 1 represents the positive class (ID) and 0 indicates OOD; λ and λ wo are typically chosen such that the true positive rate is at 95% .
For convenience, we paste the assumptions and the theorem in Section 3 below,
Assumption A.1.
Let z := 1 { y ∈ Y in } and Q x denotes the out-of-distribution P x | z
=0 (marginal distribution of x conditioned on z = 0 ).
Assume ∃ δ > 0 such that
[Equation]
where ˆ y :=
argmax i ∈ [ K ] s i ( x ) and ˆ y 2 :=
argmax i ̸
=ˆ y,i ∈
[ K ] s i ( x ) denote the indices of the largest and second largest cosine similarities for an OOD input x .
Theorem A.1.
Given a pre-trained CLIP-like model ( T , I ) and a task with label set Y in = { y 1 , y 2 , ..., y K } .
If Q x satisfy Assumption A.1, Then there exists a constant T = λ ( K − 1) ( λ wo + δ − s ˆ y 2 )
Kλ −such that for any temperature τ > T , we have:
[Equation]
where FPR( τ, λ ) is the false positive rate based on softmax scaling with temperature τ and threshold λ ; FPR wo ( λ wo ) is the false positive rate without softmax scaling based on threshold λ wo .
This suggests that applying softmax scaling with temperature results in superior OOD detection performance compared to without softmax scaling.
Proof.
By definition, we express the false positive rate FPR( τ, λ ) as follows,
[Equation]
By inequality e x ≥ 1 + x , we have,
[Equation]
This indicates
[Equation]
Since
K (cid:88) i =
[Equation] [Equation]
s i
[Equation]
x ′ ))
By Assumption 3.1, we have
[Equation] [Equation]
Therefore,
Q
[Equation]
where λ ′ = (cid:0) K − 1 λ (cid:1) τK − 1 is a monotonic function of λ ( i.e ., minimizing false positive rate w.r.t.
λ is equivalent to minimizing w.r.t.
λ ′ .)
For τ > 0 , we can rewrite the MCM score as
[Equation]
As ˆ y :
= argmax i ∈
[ K ] s i ( x ) , s j ( x ′ )
− s ˆ y ( x ′ ) ≤ 0 , S MCM ( x ′ ;
Y in , T , I ) is a monotonically decreasing function of τ , we have:
[Equation]
Therefore by the definition of λ , we have λ > 1 K , λ ′
=
(cid:0) K − 1 λ (cid:1) τK − 1 >
For moderately large τ > T where T = λ ( K − 1) ( λ wo + δ − s ˆ y 2 )
Kλ −, we always have s ˆ y 2 ( x ′ )
− δ + λ ′ >
λ wo .
Therefore, we obtain the following inequality,
[Equation]
which means that the FPR without softmax scaling is larger than that with softmax scaling and a moderately large temperature.
We show in Section 5 that the bound is indeed satisfied in practice with a large-scale ID dataset.
B Experimental Details B.1 Software and Hardware
All methods are implemented in Pytorch 1.10.
We run all OOD detection experiments on NVIDIA
GeForce RTX-2080Ti GPU and use NVIDIA A100 GPU for fine-tuning CLIP and ViT.
B.2 Hyperparameters
The only hyperparameter in MCM is the (temperature) scaling factor τ .
We use τ = 1 by default unless otherwise specified.
Our experiments suggest that MCM is insensitive to the scaling factor, where τ in a wide range of [0 . 5 , 100] shares similar performance.
B.3 Datasets
ImageNet-
We create ImageNet-10 that mimics the class distribution of CIFAR-10 but with highresolution images.
It contains the following categories (with class ID): warplane (n04552348), sports car (n04285008), brambling bird, (n01530575), Siamese cat (n02123597), antelope (n02422699),
Swiss mountain dog (n02107574), bull frog (n01641577), garbage truck (n03417042), horse (n02389026), container ship (n03095699).
ImageNet-20 For hard OOD evaluation with realistic datasets, we curate ImageNet-20, which consists of 20 classes semantically similar to ImageNet-10 ( e.g ., dog (ID) vs. wolf (OOD)).
The categories are selected based on the distance in the WordNet synsets [15].
Specifically, it contains the following categories: sailboat (n04147183), canoe (n02951358), balloon (n02782093), tank (n04389033), missile (n03773504), bullet train (n02917067), starfish (n02317335), spotted salamander (n01632458), common newt (n01630670), zebra ( n01631663), frilled lizard (n02391049), green lizard (n01693334), African crocodile (n01697457), Arctic fox ( n02120079), timber wolf (n02114367), brown bear (n02132136), moped (n03785016), steam locomotive (n04310018), space shuttle (n04266014), snowmobile (n04252077).
ImageNet-100 We randomly sample 100 classes from ImageNet-1k to curate ImageNet-100.
It contain the following categories: n01986214, n04200800, n03680355, n03208938, n02963159, n03874293, n02058221, n04612504, n02841315, n02099712, n02093754, n03649909, n02114712, n03733281, n02319095, n01978455, n04127249, n07614500, n03595614, n04542943, n02391049, n04540053, n03483316, n03146219, n02091134, n02870880, n04479046, n03347037, n02090379, n10148035, n07717556, n04487081, n04192698, n02268853, n02883205, n02002556, n04273569, n02443114, n03544143, n03697007, n04557648, n02510455, n03633091, n02174001, n02077923, n03085013, n03888605, n02279972, n04311174, n01748264, n02837789, n07613480, n02113712, n02137549, n02111129, n01689811, n02099601, n02085620, n03786901, n04476259, n12998815, n04371774, n02814533, n02009229, n02500267, n04592741, n02119789, n02090622, n02132136, n02797295, n01740131, n02951358, n04141975, n02169497, n01774750, n02128757, n02097298, n02085782, n03476684, n03095699, n04326547, n02107142, n02641379, n04081281, n06596364, n03444034, n07745940, n03876231, n09421951, n02672831, n03467068, n01530575, n03388043, n03991062, n02777292, n03710193, n09256479, n02443484, n01728572, n03903868.
Conventional (non-spurious)
OOD datasets Huang et al.
[27] curate a diverse collection of subsets from iNaturalist [69], SUN [77], Places [86], and Texture [9] as large-scale OOD datasets for
ImageNet-1k, where the classes of the test sets do not overlap with ImageNet-1k.
We provide a brief introduction to each dataset as follows.
iNaturalist contains images in the natural world [69].
It has 13 super-categories and 5,089 subcategories covering plants, insects, birds, mammals, and so on.
We use the subset that containsplant classes not overlapping with ImageNet-1k.
SUN stands for the Scene UNderstanding Dataset [77].
SUN contains 899 categories that cover more than indoor, urban, and natural places with or without human beings appearing in.
We use the subset which contains 50 natural objects not showing in ImageNet-1k.
Places is a large scene photographs dataset [86].
It contains photos that are labeled with scene semantic categories from three macro-classes: Indoor, Nature, and Urban.
The subset we use is sampled from 50 categories that are not present in ImageNet-1k.
Texture stands for the Describable Textures Dataset [9].
It contains images of textures and abstracted patterns.
As no categories overlap with ImageNet-1k, we use the entire dataset as in [27].
B.4 Baselines
For Fort et al.
[16] in Table 2, we fine-tune the whole ViT model on the ID dataset.
Specifically, we use the publicly available checkpoints from Hugging Face where the ViT model is pre-trained on
ImageNet-21k and fine-tuned on ImageNet-1k.
For example, the checkpoint for ViT-B is available at https://huggingface.co/google/vit-base-patch16-224 .
C Spurious OOD Datasets
In general, spurious attributes refer to statistically informative features that co-exist with the majority of ID samples but do not necessarily capture cues related to the labels such as color, texture, background, etc [2, 3, 18, 78, 89].
A recent work [44] investigated a new type of hard OOD samples (called spurious OOD) that contain spurious or environmental features, but no object features related to the ID classes.
A concrete example is shown in Figure 6, where images of birds co-occur frequently with either the land background or water background.
Modern neural networks can spuriously rely on the image background ( e.g ., water or land) for classification instead of learning to recognize the actual object [56].
Ming et al.
[44] show that spurious OOD samples remain challenging for most common OOD detection methods based on pure vision models such as ResNet [20].
For ID dataset, we use Waterbirds [57], which combines bird photographs from CUB-200 [73] with water or land background images from P LACES [86].
For the spurious OOD dataset, we use the one created in [44] consisting of land and water background from Places [86].
[Figure]
D ID Classification Accuracy
Table 7 shows the multi-class classification accuracy on ImageNet-1k for methods in Table
[Table] [Table]
E.1 Overview of Baselines
[Figure]
We review two previous works on CLIP-based OOD detection [14, 16] in Figure 7, which derive the scoring function based on candidate OOD labels.
For a given task with ID label set Y in = { y 1 , y 2 , ..., y K } and candidate labels Y C
=
{ y K +1 , y K +2 , ..., y K + L } , where ideally Y in ∩ Y C = ∅ , they construct a collection of text embeddings T ( t i ) , i ∈ { 1 , 2 , ..., K + L } .
Here, t i is the text prompt “ this is a photo of a ⟨ y i ⟩ ” for a label
y i .
For any test input image x , we can calculate the label-wise matching score based on the cosine similarity between the image and text features: s i ( x ) =
I ( x ) ·T ( t i ) ∥I ( x ′ ) ∥·∥T ( t i ) ∥ .
Therefore, a detection score can be derived as:
[Equation]
where τ > 0 is the temperature scaling hyperparameter.
E.2 Obtaining OOD Candidate Labels
For the baseline methods, obtaining OOD candidate labels is a major challenge and limitation.
Recently, [14] propose ZO-CLIP, where a transformer (decoder) based on the image encoder of
CLIP is used to generate candidate labels.
The transformer is trained from scratch on the COCO dataset [42] with simple teacher forcing algorithms.
Although the decoder trained on COCO may work well on CIFAR (ID), it does not scale up to large-scale datasets such as ImageNet [10] where categories are not covered in COCO.
As a result, [14] only test on small-scale datasets with common classes such as CIFAR (ID).
We improve the baseline by using a high-quality caption generator pre-trained on much larger datasets, which not only saves computational overhead but can potentially improve the quality of generated labels.
The pipeline involves three components (see Figure 8):
• A caption generator.
Given an input image, it generates a caption serving as the textual description of the input.
In this work, we consider ClipCap [45], which uses GPT-2 [54] to generate captions based on CLIP’s image encoder.
ClipCap is pre-trained on a much larger dataset Conceptual Captions [49] compared to COCO, which can be viewed as an enhanced version of the ZO-CLIP baseline [14].
The checkpoints are publicly available 3 .
• A syntactic parser.
Given a caption, we extract noun objects using a parsing toolkit released by spaCy 4 .
Those nouns can be used as candidate labels Y C of the input image.
[Figure]
• A filter module.
Unlike [14], we further enhance the baseline by adopting a filtering technique to remove overlapping categories in Y C with ID labels Y in , which we detail below.
E.3 Label Filtering
Example.
To illustrate the effects of filtering, we begin with a concrete example where ID labels are [“frog”,“bird” . . .
“truck”], as shown in Figure 8.
The generated labels (without filtering) of an ID input of a bird sitting on a tree are [“bird”, “tree”].
Therefore, Y in ∪ Y C
=
[“frog”,“bird” . . .
“truck”,“bird”, “tree”].
Ideally, the softmax probability distribution over the concatenated labels would be [0 , 0 . 5 , 0 , . . .
, 0 . 5 , 0] and by definition S ( x ) ≈ 0 .
However, if we filter the generated labels to eliminate nouns with similar meaning as ID, our concatenated labels would be [“frog”,“bird” . . .
“truck”,“tree”] and the probability vector would be [0 , 1 , 0 , . . .
, 0] , which leads to a much higher score
S ( x ) = 1 .
In contrast, the generated labels for an OOD input with a caption “man in the desert” would be [“man”, “desert”].
The resulting probability vector would be [0 , 0 , 0 , . .
, 1 , 0] and the score
S ( x ) = 0 .
Therefore, filtering makes it easier to separate ID inputs from OOD inputs ( c.f . Figure 9).
String-based filtering.
To implement the idea of filtering, we need a measurement of the similarity between the generated labels and ID labels.
The simplest way is string-based filtering where a generated label is filtered if it matches any ID labels (in the string format), as in the case above.
[Figure]
F Alternative Scoring Functions
We explore the effectiveness of several alternative scoring functions:
• Entropy: the (negative) entropy of softmax scaled cosine similarities denoted as S entropy ; • Var: the variance of the cosine similarities denoted as S var ; • Scaled: the scaled difference between the largest and second largest cosine similarities S scaled :=
e s ˆ y ( x ) − s ˆ y 2 ( x ) where ˆ
y := argmax i ∈
[ K ] s i ( x ) and ˆ y 2 :
=
argmax i ̸
=ˆ y,i ∈
[ K ] s i ( x ) .
For S entropy
[Table]
we select the temperature τ ∈ { 0 . 005 , 0 . 01 , 0 . 1 , 1 , 10 } and report the performance with the best τ .
As shown in Table 8, MCM still gives the most promising results compared to the other three alternative scores across most OOD test sets
[Table] [Table]