SemanticMIM: Marring Masked Image Modeling with Semantics Compression for General Visual Representation

## Abstract

Abstract This paper represents a neat yet effective framework, named SemanticMIM, to integrate the advantages of masked image modeling (MIM) and contrastive learning (CL) for general visual representation. We conduct a thorough comparative analysis between CL and MIM, revealing that their complementary advantages fundamentally stem from two distinct phases, i.e., compression and reconstruction.
Specifically, SemanticMIM leverages a proxy architecture that customizes interaction between image and mask tokens, bridging these two phases to achieve general visual representation with the property of abundant semantic and positional awareness. Through extensive qualitative and quantitative evaluations, we demonstrate that SemanticMIM effectively amalgamates the benefits of CL and MIM, leading to significant enhancement of performance and feature linear separability. SemanticMIM also offers notable interpretability through attention response visualization. Codes are available at https://github.com/yyk-wew/SemanticMIM .

## 1 Introduction

Self-supervised learning (SSL) algorithms Liu et al. (); Balestriero et al. () have emerged as a powerful paradigm for deriving rich feature representations without relying on extensive annotations.
These algorithms can be roughly categorized into two families: Masked Image Modeling (MIM) He et al. (); Xie et al. () and Contrastive Learning (CL) He et al. (); Chen et al. ().
As illustrated in Fig. 1, MIM focuses on the reconstruction of partially corrupted images, serving as a pretext task that facilitates the model’s ability to infer local patterns from contextual information rather than grasping global semantics Li et al. (); Xie et al. (). MIM is inherently compatible with the transformer architecture and demonstrates versatility across different tasks and modalities, thereby garnering increasing research interest.
In contrast, Contrastive Learning emphasizes aligning global features with instance discrimination as its core pretext task Wu et al. ().
CL excels in capturing prominent, semantically rich foreground elements, albeit at the expense of nuanced understanding of complex local spatial patterns. Further, the absence of positional priors in the pre-training implies that CL’s semantic understanding is broadly homogeneous, circumventing the need for explicit positional awareness. Consequently, MIM and CL exhibit specialization in downstream tasks that are sensitive to positional dynamics (e.g., segmentation) and semantic content (e.g., classification), respectively. Given the distinct advantages and limitations of MIM and CL, there exists a compelling imperative to integrate these complementary approaches.

Prior efforts to reconcile the disparities between MIM and CL have predominantly adopted two strategies. First, one approach sought to augment CL with fine-grained alignment with positional priors, such as aligning features of pixels, regions, or objects Wang et al. (); Van Gansbeke et al. (); Bai et al. ().
However, this CL-centric strategy suffers from collapse to trivial solutions and thus heavily relies on hyperparameters and regularization, thereby sacrificing the inherent flexibility of MIM.
Second, a more straightforward strategy is optimizing the objectives of MIM and CL simultaneously Zhou et al. (); Oquab et al. ().
This approach inevitably introduces the complex task of integrating two distinct learning objectives and the pursuit of multi-view representation significantly escalates the computational demands, which necessitates a nuanced approach to balance and fuse these methodologies.

To deepen the understanding of the intrinsic properties of MIM and CL, we explore their specifics empirically in Sec. 3.2. We elucidate that the complementary capabilities of CL and MIM methods in semantic modeling, i.e., consistency and completeness are achieved through compression and reconstruction, respectively.
CL approaches compress information from all image patch tokens [IMG] into a single class token [CLS] , encapsulating global abstract semantics. Conversely, reconstruction-based MIM methods prioritize local neighbors rather than global semantics, stemming from the inherent redundancy in image modality.

SemanticMIM introduces a novel paradigm by integrating the merits of CL within MIM framework, facilitated by a neat yet effective proxy architecture. The key is to harmonize compression and reconstruction within a single learning framework rather than a multi-task manner. Specifically, we propose a proxy architecture to seamlessly connect two phases: initially, [IMG] tokens interact with [PROXY] tokens, compressing all information into the [PROXY] tokens, which embody abstract semantics. Subsequently, these [PROXY] tokens engage with the mask tokens [MASK] , reconstructing the target with spatial priors derived from [MASK] tokens while preserving rich semantics through the [PROXY] tokens.

We conduct a broad spectrum of both qualitative and quantitative analyses to substantiate the efficacy of SemanticMIM. The following points delineate the advantages of SemanticMIM. (1) Compared to MIM, SemanticMIM excels in discerning the semantics of specific objects rather than semanticless neighbor pixels, i.e., consistency. (2) Compared to CL, SemanticMIM exhibits a keen positional awareness rather than homogeneous perception. It adeptly identifies targeted semantics within both foreground and background elements with explicit positional priors, i.e., completeness. (3) The [PROXY] tokens tend to inherently learn various implicit positional priors, i.e., regions of interest.
This mechanism naturally directs the model’s attention towards relevant semantic features, substantially simplifying the challenge of exploring a broader context.
(4) Beyond achieving considerable performance gains in fine-tuning settings, SemanticMIM significantly improves the performance in linear probing settings, which indicates that the features of pre-training phase are more linearly separable.

The main contributions are summarized as follows:

- •
We provide an elaborate analysis, and point out that the fundamental principles underlying contrastive learning and masked image modeling lie in compression and reconstruction, respectively.
- •
We propose SemanticMIM, a neat yet effective framework to integrate the merits of masked image modeling and contrastive learning. SemanticMIM leverages a proxy architecture to orchestrate compression and reconstruction in cascades.
- •
Extensive qualitative and quantitative experiments validate the effectiveness of SemanticMIM, indicating its capability of obtaining visual representations with high consistency and completeness.

## 2 Related Work

### 2.1 Masked Image Modeling

Motivated by the success of Masked Language Modeling in NLP Devlin et al. (), Masked Image Modeling (MIM) has been proposed for training a vision transformer in a self-supervised manner. For MIM task, the model takes a corrupted image as input and predicts the target of the missing area. The difference between the prior works of MIM mainly lies in the target choice and image corruption.

Target can be roughly divided into two kinds: low-level signals and high-level features. The former mainly refers to raw pixels Dosovitskiy et al. (); Xie et al. (); Huang et al. (), normalized pixels He et al. (), hand-crafted feature descriptors Wei et al. (), and even positions Zhai et al. (); Caron et al. (); Wang et al. (). This kind of target is easy to obtain with no extra cost but continuous signals suffer from high redundancy and few semantic information. Researchers find that high-level features extracted by well-trained image tokenizers are also appropriate targets, including concrete deep features by offline  Wei et al. (; ); Zhou et al. (); Hou et al. (); Peng et al. () or online models Tao et al. (); Chen et al. (); Dong et al. (); Zhou et al. () and discrete codes Bao et al. (); Chen et al. (); Dong et al. () generated by VQ-VAE Van Den Oord et al. () or dVAE Ramesh et al. ().

The most used image corruption strategy is randomly removing a certain proportion of image patches. On this basis, removing multiple adjacent patches creates a more challenging context and encourages long-range dependency Bao et al. (); Xie et al. (). Inspired by hard sample mining, manually designed criterions are proposed to choose where to mask and guide the model reconstructing the discriminative image patches Kakogeorgiou et al. (); Shi et al. (); Li et al. (). Furthermore, image corruption could also be processed in the frequency domain, transforming the pretext task into low-level vision tasks such as image super-resolution or denoising Xie et al. ().

### 2.2 Contrastive Learning

Contrastive learning (CL) methods He et al. (); Chen et al. (; ); Chen* et al. (); Chen et al. () learn visual representations by creating different views of an image and aligning their features, encouraging semantic invariance to simple transformations.
To resist collapse to trivial solutions, the contrastive loss Wu et al. (); Oord et al. () is adopted to maximize dissimilarity between negative sample pairs.
The introduction of prototypes Li et al. (); Asano et al. (); Caron et al. () addresses the large batch size requirement by replacing pairwise comparison with cluster assignment consistency.
Self-distillation methods Grill et al. (); Caron et al. (); Oquab et al. (); Chen & He () further simplify the training framework, preventing collapse by asymmetric model architecture and parameter update strategy.
Besides, more regularizations Zbontar et al. (); Bardes et al. (); Oquab et al. () are proposed to constrain correlations in the dimensions of not only samples but also features.

On the other hand, CL is sub-optimal for dense prediction downstream tasks due to the discrepancy between image-level alignment pre-training and pixel-level prediction.
Hence, dense contrastive learning methods are proposed aligning sub-image-level features with position priors.
Pixel-level (point-level) features are easily obtained on feature maps before pooling and matched between views by designed rules such as similarity or spatial distance Wang et al. (); O Pinheiro et al. (); Xie et al. (); Zhang et al. (); Ziegler & Asano ().
With the help of masks or regions of interest generated by unsupervised segmentation and detection modules, object-level feature alignment further benefits the localization and intra-image contrast Van Gansbeke et al. (); Hénaff et al. (); Huang et al. (); Roh et al. (); Xie et al. (); Wei et al. ().
Creating synthetic views by copying regions from other images like mixup augmentation Zhang et al. () could also obtain prior foreground masks Wang et al. (); Yang et al. ().
However, most of the above feature alignments are combined with the original image-level loss. How to balance multi-level supervision and avoid over-weight remains further exploration.

## 3 Method

Figure: Figure 2: A unified view of the masked image modeling (i.e., BEiT) and contrastive learning (i.e., MoCov3) paradigm.
Refer to caption: x2.png

### 3.1 A Unified View of Self-Supervised Learning Framework

In this section, we present a unified view of the self-supervised learning (SSL) framework, aiming to harmonize the merits of masked image modeling (MIM) and contrastive learning (CL).

The MIM framework generally consists of four principal components: an augment operator, an encoder, a prediction head, and a target generator.
As shown in Fig. 2 (a), an input image $\bm{x}$ is augmented by random masking to remove a certain proportion of image patches.
Define the index set of all image patches as $\bm{I}=\{1,\dots,N_{\texttt{[IMG]}}\}$, the index set of the remaining image patches and discarded image patches as $\bm{R}_{\texttt{[IMG]}}\subseteq\bm{I}$ and $\bm{R}_{\texttt{[MASK]}}=\bm{I}-\bm{R}_{\texttt{[IMG]}}$, respectively.
The retained patches are projected into a series of patch embeddings $\{\bm{x}_{i}\}$, whereas the discarded ones are substituted with the equivalent number of repeated learnable query tokens, known as [MASK] tokens in MIM. After applying positional embeddings to the sequence according to their position index from $\bm{R}_{\texttt{[IMG]}}$ and $\bm{R}_{\texttt{[MASK]}}$, the whole sequence is then processed by the encoder and the prediction head.
Meanwhile, the target generator takes the complete original image as input and generates the dense target $\bm{t}_{i}$, i.e., the supervision signal. Finally, the reconstructed [MASK] tokens, restoring the semantic information of the corresponding missing patches, are supervised by the generated target with the designated similarity measure $\mathcal{L}$. The objective function is delineated as follows:

$$ $\min\mathop{\mathbb{E}}_{\bm{x}\in\mathcal{D}}\mathop{\mathbb{E}}_{i\in\bm{R}_ {\texttt{[MASK]}}}\mathcal{L}(\bm{z}_{i},\bm{t}_{i}),$ (1) $$

where $\mathcal{D}$ is the training corpus and $\bm{z}$ is the output feature of the prediction head.
The choice of the $\mathcal{L}$ depends on the target used. For example, $\ell_{1}$ is used when using pixel Xie et al. () or HOG Wei et al. () as targets, and cross-entropy is used when the target is produced by discrete tokenizers such as dVAE Bao et al. () or VQGAN Dong et al. ().

Further, we find that the CL methods, particularly those employing self-distillation manner, share a similar framework as MIM methods as illustrated in Fig. 2(b).
For example, MoCo Chen* et al. (), a typical CL approach, employs augmentation techniques such as random resized cropping to generate multiple views of an input image.
The query to obtain representation with global semantics is a single learnable embedding, known as [CLS] token in vision transformer. The target generator is a dual online encoder updated by exponential moving average (EMA). The generated deep feature target is aligned with the output query token by contrastive lossOord et al. ().

Both methodologies adhere to a common paradigm of extracting and aligning features from augmented views of the same image. The main difference lies in the access of features and type of target. More specifically, MIM uses several queries with positional prior to focus on local neighbor pixels with positional awareness and uses dense target for supervision, whereas CL only uses a single query without prior to obtain features with global semantics and uses image-level target.
Previous works have demonstrated that the four components of the framework are replaceable between MIM and CL methods.
For instance, the dual EMA encoder in CL could also serve as the target generator in MIM Tao et al. (); Chen et al. (); Dong et al. (); Zhou et al. (), and the masking operation in MIM can join the augmentation series in CL to generate more challenging views Assran et al. (); Huang et al. (); Shen et al. ().
This cross-utilization highlights the flexibility and shared foundational principles of both methodologies.

Figure: Figure 3: Information propagation of the contrastive learning, masked image modeling, and our proposed SemanticMIM.
Refer to caption: x3.png

### 3.2 Discussion on Properties of Self-supervised Learning Framework

Self-supervised learning aims to train models that exhibit robust generalization across various downstream tasks. To give a more specific definition, an ideal pre-trained model is expected to be capable of encoding features of promising consistency and completeness.
Consistency ensures that queries on identical objects elicit similar responses.
Completeness guarantees that arbitrary objects within an image, including often overlooked backgrounds, should be encoded into features of the corresponding positions.

CL methods exhibit promising consistency but poor completeness. They could adeptly capture the salient objects. However, this focus comes at the expense of completeness, as they tend to neglect the details of the background. In contrast, MIM achieves high completeness by capturing detailed representations across the entire image but struggles with consistency.
More specifically, the redundancy in features of MIM means they are more likely to exhibit response by neighbor patches rather than those of similar semantics.
For example, as shown in Fig. 1, the features from different parts of the sky exhibit dissimilarity despite belonging to the same object “sky”. The low consistency underlines MIM’s challenge in capturing global semantic representations.

From Sec. 3.1, we have pointed out that the main difference between MIM and CL stems fundamentally from their distinct target and query. This section delves into how target and query contribute to consistency and completeness.

Dense target encourages completeness but reduces consistency. Regardless of the specific target generator employed, MIM inherently produces dense targets characterized by significant redundancy. More specifically, This redundancy implies that the targets for neighboring areas bear a strong similarity to each other.
This phenomenon essentially degenerates MIM into a variant of an autoencoder, where the model (i.e., [MASK] query) tends to replicate its neighbors.
We identify it as a “learning shortcut” inherent to MIM, leading to a limited receptive field that inadvertently encourages a model to mimic the properties of adjacent areas rather than understanding the broader context.

To mitigate this issue, most MIM framework adopts a high mask ratio to reduce the probability that adjacent patches exist and compel the model to extend its focus to the broader context rather than local neighbors. Advanced masking strategy (e.g., SimMIMXie et al. ()) is also designed to exclude adjacent patches by using the mask unit of larger size.
But as the attention response shown in the Fig. 1, not all features belonging to a specific object have high similarity but only those adjacent in spatial do, indicating that the MIM model still tends to focus on local areas and struggles with low consistency.

Global target encourages consistency but reduces completeness. CL methods utilize a single global feature as the target, generated either by a sophisticatedly trained model or an online EMA updated encoder. This global feature target typically encapsulates the essence of the foreground at the detriment of background details.
Meanwhile, compared to the dense supervision of MIM, a single target feature in CL is high-level and more conceptual, raising properties that explicitly contain the foreground layout of high consistency.

Query in CL acts compression and queries in MIM find neighbors. We provide analysis from the perspective of information propagation.
In CL, the [CLS] token serves as the query, embodying a mechanism that captures global semantics and generates abstract features.
Its capability is empowered by the implicit compression during forwarding, as shown in Fig. 3(a).
[CLS] token is tasked with compressing information from all relevant image patches, aligning itself with targets that encapsulate global context. This compression phase helps the model retain the most essential information and reduce feature redundancy.
This single query token [CLS], however, provides limited capacity and over compress information.

Conversely, MIM employs learnable semantic-free embeddings, the [MASK] tokens as queries. Distinct from the query in CL, the [MASK] tokens are applied with position embeddings as prior to indicate target reconstruction areas. However, the prior inadvertently encourages convenience to the “learning shortcut” mentioned in the last section, making it effortless for the model to locate the neighboring image patches of the masked patches and reduce the necessity of leveraging broader contexts.
As depicted in Fig. 3(b), when the queries only propagate information with a limited number of neighboring image patches, the pre-trained model of MIM performs poor feature consistency and notable redundancy without the help of compression.

Figure: Figure 4: Comparison of the architecture between masked image modeling and our proposed SemanticMIM. MIM only focuses on Reconstruction. SemanticMIM contains two cascaded phases via proxy, i.e.,Compression (left) and Reconstruction (right). Besides, The modules of the Reconstruction (right) phase are discarded after pre-training.
Refer to caption: x4.png

### 3.3 Masked Image Modeling with Proxy Architecture

Based on the provided analysis, we propose a neat framework SemanticMIM drawing inspiration from the compression of CL and applying it to solve the inherent limitations of MIM, as shown in Fig. 3(c). To mitigate the issue of easily locating neighboring image patches of the masked patches due to the positional prior, we disrupt the direct information propagation between [IMG] tokens and the [MASK] tokens. Instead, we leverage extra tokens with no positional prior in between as a proxy, naming it [PROXY] token. Second, since the [PROXY] tokens and [MASK] tokens are both queries with no semantic information, the information is forced to spread from [IMG] tokens to [PROXY] tokens and then from [PROXY] tokens to [MASK] tokens. The [PROXY] token plays a role in the information bottleneck and thus the original pretext task is divided into two distinct stages: compression and reconstruction. We can calibrate the extent of compression by adjusting the number of [PROXY] tokens used.

The implementation is shown in Fig. 4.
In the original MIM framework, [IMG] and [MASK] tokens are processed as a whole sequence. Suppose the hidden state of the [IMG] and [MASK] tokens of layer $i$ as $\bm{h}^{i}_{\texttt{[IMG]}}$ and $\bm{h}^{i}_{\texttt{[MASK]}}$, respectively. The forward process in each transformer layer is defined as follows:

$$ $\bm{h}^{i+1}_{\texttt{[IMG]}},\bm{h}^{i+1}_{\texttt{[MASK]}}=\mathrm{MLP}( \mathrm{SelfAttn}([\bm{h}^{i}_{\texttt{[IMG]}},\bm{h}^{i}_{\texttt{[MASK]}}])).$ (2) $$

The key idea of SemanticMIM is a specific mechanism of information propagation constraint. For the three types of tokens, our goal is to architecturally segregate [IMG] and [MASK] , rendering them mutually exclusive in visibility, while simultaneously ensuring both are accessible to [PROXY] tokens.
This is achieved through a modification of the transformer block, as illustrated in Fig. 4(b), which incorporates dual cascaded attention and MLP modules, mirroring settings across each layer.
The self-attention and subsequent MLP only process [IMG] and [PROXY] tokens, responsible for the compression task, gathering semantic information from image patches and compressing it into [PROXY] tokens. This forward can be formulated as follows:

$$ $\bm{h}^{i+1}_{\texttt{[IMG]}},\bm{h}^{i+1}_{\texttt{[PROXY]}}=\mathrm{MLP}( \mathrm{SelfAttn}([\bm{h}^{i}_{\texttt{[IMG]}},\bm{h}^{i}_{\texttt{[PROXY]}}])),$ (3) $$

where $\bm{h}^{i}_{\texttt{[PROXY]}}$ is the hidden state of the [PROXY] token at layer $i$.
The extra cross-attention and the following MLP finish the reconstruction task. In particular, the sequence formed by concatenating [PROXY] and [MASK] tokens is utilized as key and value, while only the [MASK] token serves as query input. We formulate this process as follows:

$$ $\bm{h}^{i+1}_{\texttt{[MASK]}}=\mathrm{MLP}(\mathrm{CrossAttn}(\bm{h}^{i}_{ \texttt{[MASK]}},[\bm{h}^{i+1}_{\texttt{[PROXY]}},\bm{h}^{i}_{\texttt{[MASK]}} ])).$ (4) $$

With this design, the compression and reconstruction task is fully disentangled and executed by independent modules. Such disentanglement makes the reconstruction modules serve as a dedicated plugin for the pre-training stage and can be discarded later. Besides, the compression part follows the same architecture as a vanilla vision transformer, where the [PROXY] token can be implemented by simply using the [CLS] token, maintaining consistency with downstream tasks.
Further, the encoder only performs the compression task in our framework, avoiding wasting capacity on the reconstruction task as in the original MIM framework Liu et al. ().
Our design better meets the requirements of the downstream tasks for discriminative visual representations with consistency and completeness defined in Sec. 3.2.

## 4 Experiments

### 4.1 Pre-training Setting

As our proposed method only modifies the encoder architecture, it can be applied to any MIM framework. To illustrate the generality, we choose two representative baselines BEiT Bao et al. () and Maskfeat Wei et al. (), which utilize high-level and low-level targets respectively.
For all experiments, we use ViT-Base Dosovitskiy et al. () with patch size $16$ as the encoder backbone and pretrain it on ImageNet-1K Deng et al. () dataset over $300$ epochs at $224^{2}$ resolution. We reproduce the BEiT and Maskfeat following their training setting, except that absolute position embedding and random patch masking strategy are used for simplicity. Both baselines adopt 40% mask ratio and 1 [CLS] token.

Since our proposed [PROXY] token is indeed a series of learnable embedding just like the [CLS] token, in the implementation, we initialize multiple [CLS] tokens and use them as the [PROXY] tokens.
When applying our methods to the baseline, we retain the original training recipes, but set the mask ratio to 60% and the number of [CLS] tokens (i.e., [PROXY] tokens) to 8.
The model used in ablation study and visualization is based on BEiT unless specified otherwise.
Further details on our pre-training are provided in the  Appendix C.

### 4.2 Evaluation Settings

To quantitatively validate the effectiveness of our methods, we conduct experiments on classification and semantic segmentation tasks with both linear probing and end-to-end fine-tuning.

For the classification task, we train a supervised linear classifier on the ImageNet-1K training set for $100$ epochs and report top-1 accuracy on the ImageNet-1K validation set following the settings in Bao et al. ().
The classifier is integrated at the final layer under the fine-tuning protocol and at the $7^{th}$ layer to harness a generalizable feature representation under the linear probing protocol.
Additionally, we provide results of feeding the classifier with average pooling features of output [IMG] and [CLS] tokens, respectively.

For the semantic segmentation task, we report mIoU on ADE20K Zhou et al. () benchmark with 150 semantic categories for end-to-end fine-tuning and PascalVOC Everingham et al. () benchmark with 21 semantic categories for linear probing. More specifically, on ADE20K, we use UperNet Xiao et al. () as the decoder and fine-tuning for 160k steps at $640^{2}$ resolution following Bao et al. (). On PascalVOC, we train a $1\times 1$ conv layer on top of the frozen 6-th layer feature at $448^{2}$ resolution for 25 epochs following Ziegler & Asano ().

Further details of all the above protocols are described in the  Appendix C.

### 4.3 Main Results

**Table 1: Performance comparison with baselines. We report top-1 accuracy on ImageNet-1K, mIoU on ADE20K, and mIoU on PascalVOC. Linear and FT stand for linear probing and fine-tuning, respectively. All results are produced by ourselves.**
| Datasets | ImageNet-1K | PascalVOC | ADE20K |  |  |  |
| --- | --- | --- | --- | --- | --- | --- |
| Protocol | Linear | FT | Linear | FT |  |  |
| Feature | CLS | Patch | CLS | Patch | Featmap | Featmap |
| BEiT | 31.5 | 38.7 | 81.9 | 82.2 | 23.8 | 40.2 |
| BEiT + Ours | 49.2(+17.7) | 48.2(+9.5) | 83.0(+1.1) | 82.9(+0.7) | 43.1(+19.3) | 44.1(+3.9) |
| MaskFeat | 23.4 | 33.5 | 82.7 | 83.0 | 37.8 | 42.6 |
| MaskFeat + Ours | 52.0(+28.6) | 59.7(+26.2) | 83.7(+1.0) | 83.6(+0.6) | 49.5(+11.7) | 45.7(+3.1) |

We validate our proposed SemanticMIM by incorporating it to BEiT and MaskFeat in Tab. 1. On classification, SemanticMIM enhances accuracy by 10% for BEiT and 25% for MaskFeat during linear probing, and around 1% under fine-tuning. On segmentation, our method outperforms BEiT by 19.3% and Maskfeat by 11.7% under linear probing and around 3% under fine-tuning.

Three findings emerge from the results. First, SemanticMIM notably enhances performance under linear probing, a protocol that directly assesses the quality of visual representations, indicating that SemanticMIM learns more linearly separable and discriminative features.
Second, our method shows a more pronounced improvement on MaskFeat compared to BEiT.
This discrepancy can be attributed to MaskFeat’s use of low-level HOG targets, which possess less semantic information and greater redundancy, leading to features encoding with more details but poor consistency.
Compression introduced in our framework is particularly effective for this scenario, yielding substantial performance enhancements.
Thirdly, with our method, the [CLS] tokens become more adept at extracting global information and perform better than before, since [CLS] token serves as the proxy to effectively gather information from context and learn compressed semantic features without supervision.

Note that the baseline performance of our reproduced BEiT and MaskFeat is lower than reported in the original paper and it is mainly due to the different settings. BEiT and MaskFeat use block-wise masking and undergo training for 800 and 1600 epochs, respectively. Our study employs random patch masking and limits training to 300 epochs for simplification purposes.

Figure: Figure 5: Number of [CLS] token. The y-axes are ImageNet-1K validation accuracy (%) under fine-tuning protocol.
Refer to caption: x5.png

### 4.4 Ablation Study on Number of [PROXY] Token

Fig. 6 shows the impact of the number of [CLS] token, i.e. [PROXY] token in our method. We train ViT-Base with a mask ratio of 60% for 300 epochs and then fine-tune for 100 epochs.
As the number of [PROXY] tokens increases, the extent of compression decreases, more information is transferred to the [MASK] token for reconstruction and thus the task difficulty is reduced.
The optimal performance is achieved with 8 [PROXY] tokens. SemanticMIM with only 2 [PROXY] tokens achieves competitive performance to the baseline, indicating high redundancy of the original image context.
With more [PROXY] tokens, the effect of compression gradually diminishes.
Considering the extreme case of using as many [PROXY] tokens as [MASK] tokens or even more, our method degenerates to the conventional MIM except for an extra information exchange between [PROXY] and [MASK] token.
Hence, the performance of our methods gradually approaches the baseline as the number of [PROXY] tokens increases.

### 4.5 Ablation Study on Mask Ratio

Fig. 6 shows the effect of the mask ratio. We train ViT-Base with 8 [PROXY] tokens for 300 epochs and then fine-tune for 100 epochs.
A low mask ratio leads to overly rich context information rendering the pretext task insufficiently challenging, and vice versa for a high mask ratio.
The optimal ratio of our method is around 60%.
Previous works whose encoder processes only visible patches use a higher ratio like 75% in MAE He et al. () and those processing the whole sequence including [MASK] tokens use a lower mask ratio like 40% in BEiT Bao et al. ().
Our architecture is similar to MAE, in which the encoder does not process [MASK] tokens. As we incorporate information bottleneck via [PROXY] tokens, the difficulty of the pretext task increases compared to the original MIM framework and thus the optimal mask ratio is lower.

## 5 Visualization

In this section, we provide a qualitative analysis by visualizing the attention response of the pre-trained models. We compare MoCov3 Chen* et al. (), BEiT Bao et al. (), and our method based on BEiT to explore the properties of CL, MIM, and the proposed SemanticMIM. More examples are provided in the  Appendix B.

Figure: Figure 7: Attention maps queried by distinct patches across different methods. We select four patches as queries and produce four attention maps on each method. The position of the query to produce each map is marked with red boxes.
Refer to caption: x7.png

Figure: Figure 8: Attention maps queried by [CLS] /[PROXY] across different methods.
Refer to caption: x8.png

SemanticMIM satisfies both completeness and consistency. As shown in Fig. 7, we visualize the attention map with [IMG] as queries.
MoCov3 displays a lack of positional sensitivity and generates homogeneous attention maps that distinguish foreground and background regardless of which image patch to query.
BEiT suffers from local receptive fields and only neighbor image patches respond to the query.
SemanticMIM integrates the advantages of both, being position-aware and semantic-aware. All [IMG] tokens belonging to the same object as the given patch respond to the query, which illustrates the remarkable consistency. Besides, all objects in the foreground and background have correct and distinct responses, showcasing strong completeness.
Moreover, a notable observation is that SemanticMIM assigns similar features to the two cats with different appearances, underscoring its capability of semantic perception.

Figure: Figure 9: Heatmap of the focused area of distinct [PROXY] tokens. We average the attention map of 500 images from ImageNet to display this pattern.
Refer to caption: x9.png

Deciphering the intrinsic mechanism of SemanticMIM. Fig. 8 unveils the attention response of the [PROXY] token.
Supervised by the global deep feature target, the [CLS] token of MoCov3 focuses on the foreground, including the trees and the tower.
In contrast, BEiT lacks explicit [CLS] token supervision and the disorderly attention response illustrates that it struggles to gather semantic information.
For SemanticMIM, different [PROXY] tokens pay attention to objects of different regions and most of the patches respond to the query in each attention map belonging to the corresponding semantic category.

Delving deeper, we calculate the average attention map of each [PROXY] token over 500 images from ImageNet, and the result is shown in Fig. 9.
It is observed that each [PROXY] token focuses on almost exclusive regions.
Since an image patch of arbitrary position may be selected for reconstruction, the [PROXY] tokens, the only information provider for the mask tokens, are forced to encode information of all regions.
The most efficient encoding method is that each [PROXY] tokens store information of distinct areas non-overlappingly.
Hence, the [PROXY] tokens in SemanticMIM tend to region-level object queries with position prior, gathering semantic information from regions of interest, which facilitates the reconstruction by encouraging [MASK] token to explore region-level context.

Figure: Figure 10: Attention maps of SemanticMIM across depths. The patches used as queries are marked with red boxes and the depth refers to the layer index.
Refer to caption: x10.png

Attentions grow from local to global across depth in SemanticMIM.
As shown in Fig. 10, we visualize the attention map across various layers. It indicates that attention in the shallow layers predominantly focuses on the local neighbors of the query patch.
With the depth increases, the response area in the attention map gradually broadens, indicating that the model progressively explores the context with further spatial distance. Finally, the attention map converges to the semantic layout of the corresponding object. Previous work Xie et al. () has shown that supervised pre-trained and CL pre-trained models tend to exhibit a shift from local to global focus across layers but MIM pre-trained model brings locality inductive bias. SemanticMIM follows the framework of MIM and behaves like CL and supervised pre-training, indicating that compression is crucial to the global receptive field.

## 6 Conclusion and Limitations

In this paper, we present SemanticMIM to integrate the merit of contrastive learning into masked image modeling. We first abstract the essence of CL and MIM to compression and reconstruction through comprehensive analysis. With this hypothesis, SemanticMIM naturally leverages a proxy architecture to first compress all information of [IMG] token into [PROXY] token, and reconstruct [MASK] token conditioned on these [PROXY] token. As a result, SemanticMIM adeptly models global semantics akin to contrastive learning, while preserving the spatial awareness intrinsic to masked image modeling, leading to a general self-supervised visual representation.
Further, extensive qualitative and quantitative experiments validate the effectiveness of SemanticMIM.

For limitations, we have identified that the masking ratio plays a pivotal role in performance. Unlike traditional MIM, where the set of image patch indices is strictly non-overlapping with the mask token indices to prevent mere replication, SemanticMIM permits overlap between these sets.
We hypothesize that two hyperparameters controlling the ratio of [IMG] and [MASK] tokens can enable rich semantic context and sufficient reconstruction simultaneously. We shall explore it to improve the framework flexibility in future work.

## Appendix A Analysis on Attention Distance

Following Xie et al. (), we analyze the average attention distance across models pre-trained by three distinct methods, i.e. MIM (BEiT), CL (MoCov3), and our proposed SemanticMIM, as shown in Fig. 14. The attention distance is computed by averaging the distance between the query patch and all other patches, weighted by the attention weights Dosovitskiy et al. (). It is analogous to the receptive field where higher value refers to a broader context dependency.

We observe that CL pre-trained models tend to focus on the local context at lower layers, transitioning to more global context at higher layers, while MIM pre-trained models display an opposite trend.
SemanticMIM, although grounded in MIM’s training architecture, exhibits a pattern akin to CL, suggesting that data compression plays a pivotal role in managing context dependency.
Meanwhile, SemanticMIM retains MIM’s characteristic of diverse head behaviors across all layers.
Finally, it is observed that the average attention distance of SemanticMIM is higher than MIM and lower than CL. We argue that MIM might overly concentrate on neighboring patches, while in CL the entire foreground containing multiple objects responds to the query. SemanticMIM can distinguish objects of different semantic categories, leading to a balanced attention distance.

Figure: Figure 11: BEiT.
Refer to caption: x11.png

## Appendix B Visualization

In this section, we present more attention visualization results in Figs. 15 and 16. We pre-train a ViT-Base model with our proposed SemanticMIM framework based on BEiT on ImageNet-1K for 300 epochs. We evaluate SemanticMIM under both simple and complex scenarios without selective cherry-pick.

## Appendix C Detailed Recipes

We provide the detailed recipe of pre-training in Tab. 2 and all four evaluation experiments in Tab. 3, Tab. 4, Tab. 5, and Tab. 6.

Figure: Figure 15: Attention maps of complex scenarios. We select several different styled images from LAION Schuhmann et al. (), containing multiple objects as inputs. The queried patches are marked with red boxes.
Refer to caption: x14.png

Figure: Figure 16: Attention maps of images containing a single object. We select several images commonly used in fine-grained classification tasks. The queried patches are marked with red boxes.
Refer to caption: x15.png

**Table 2: Hyperparameters for pre-training BEiT and MaskFeat on ImageNet-1K. When applying our proposed method, we use exactly the same recipe.**
| Hyperparameters | BEiT | MaskFeat |
| --- | --- | --- |
| Training epochs | 300 |  |
| Batch size | 2048 |  |
| Adam $\epsilon$ | 1e-8 |  |
| Adam $\beta$ | (0.9, 0.999) |  |
| Peak learning rate | 1.5e-3 | 1.6e-3 |
| Minimal learning rate | 1e-5 | 1e-6 |
| Learning rate schedule | Cosine |  |
| Warmup epochs | 10 | 30 |
| Gradient clipping | 3.0 | 0.02 |
| Stoch. depth | 0.1 |  |
| Weight decay | 0.05 |  |
| Crop Ratio | (0.08, 1.0) | (0.5, 1.0) |
| Flip Prob | 0.5 |  |
| Color jitter | 0.4 | ✗ |

**Table 3: Hyperparameters for fine-tuning pre-trained model on ImageNet-1K.**
| Hyperparameters | BEiT & MaskFeat |
| --- | --- |
| Epochs | 100 |
| Batch size | 1024 |
| Adam $\epsilon$ | 1e-8 |
| Adam $\beta$ | (0.9, 0.999) |
| Peak learning rate | 4e-3 |
| Minimal learning rate | 0 |
| Learning rate schedule | Cosine |
| Warmup epochs | 0 |
| Gradient clipping | ✗ |
| Stoch. depth | 0.1 |
| Weight decay | 1e-4 |
| Crop Ratio | (0.08, 1.0) |
| Flip Prob. | 0.5 |

**Table 4: Hyperparameters for fine-tuning pre-trained model with UperNet on ADE20K. BEiT and MaskFeat use the same recipe.**
| Hyperparameters | BEiT & MaskFeat |
| --- | --- |
| Fine-tuning Steps | 160k |
| Batch size | 16 |
| Adam $\epsilon$ | 1e-8 |
| Adam $\beta$ | (0.9, 0.999) |
| Peak learning rate | 3e-5 |
| Minimal learning rate | 0 |
| Learning rate schedule | Linear |
| Warmup steps | 1500 |
| Gradient clipping | ✗ |
| Stoch. depth | 0.1 |
| Weight decay | 0.05 |
| Input resolution | $640\times 640$ |
| Multi-scale Inference | ✗ |

**Table 5: Hyperparameters for training the classifier while freezing the pre-trained model following linear probing protocol on ImageNet-1K. BEiT and MaskFeat use the same recipe.**
| Hyperparameters | BEiT & MaskFeat |
| --- | --- |
| Epochs | 100 |
| Batch size | 1024 |
| Adam $\epsilon$ | 1e-8 |
| Adam $\beta$ | (0.9, 0.999) |
| Peak learning rate | 4e-3 |
| Minimal learning rate | 0 |
| Learning rate schedule | Cosine |
| Warmup epochs | 0 |
| Gradient clipping | ✗ |
| Weight decay | 1e-4 |
| Crop Ratio | (0.08, 1.0) |
| Flip Prob. | 0.5 |

**Table 6: Hyperparameters for training the segment head while freezing the pre-trained model following linear probing protocol on PascalVOC. BEiT and MaskFeat use the same recipe. For faster training, we interpolate the groundtruth and output to training resolution and use normal eval resolution during evaluation.**
| Hyperparameters | BEiT & MaskFeat |
| --- | --- |
| Epochs | 25 |
| Batch size | 120 |
| Optimizer | SGD |
| Learning rate | 0.01 |
| Learning rate schedule | Step |
| Warmup epochs | 0 |
| Gradient clipping | ✗ |
| Weight decay | ✗ |
| Input resolution | $448\times 448$ |
| Training resolution | $100\times 100$ |
| Eval resolution | $448\times 448$ |
| Multi-scale Inference | ✗ |

## Peer Reviews

confidence: 3
contribution: 3
initial_rating: 6
presentation: 2
questions: 1. The layout of Fig. 1 can be changed to fit its goal of comparing MIM and CL as the following.
Image A BeiT-A MoCov-A Ours-A
Image B BeiT-B MoCov-B Ours-B
The current layout is confusing at first glance since A and B are "up vs. down" on the left subfigure but "left vs. right" on the right subfigure.

2. Fig. 1 needs a clearer caption to explain it. The caption does not explain what the reader should be observing here. In what way is "ours" better than the baselines? The paper only explains it later in L49, L246, and L264. Moreover, in L49, how does a reader realize the following claim "MIM focuses on the reconstruction of partially corrupted images, serving as a pretext task that facilitates the model’s ability to infer local patterns from contextual information rather than grasping global semantics" from the figure? The color yellow for the boxes is too similar to the chosen colormap.

3. Fig. 2 can be also made clearer. What is the purpose of the target generators here? What is being trained? The [CLS] tokens and [MASK] tokens should be indicated in this figure. The token color of Fig.2 and Fig.3 should match.

4. In Fig 3, why does the [MASK] token in MIM go straight to [TARGET]? As in Fig. 2, same as CL, MIM also outputs some tokens (blue). The major difference of [MASK] token having positional embedding should be indicated in Fig.2 or 3.

5. In L262, there is a missing space between SimMIM and the citation.

6. In Fig. 4, it does not seem like compression for SemanticsMIM since the number of [MASK] matches the number of [IMG].

7. In L344, semanticMIM -> SemanticMIM.

8. The baselines seem outdated (2021~2022). Can SemanticMIM be compared to [1] or [2]?

9. In the experiment section, why use the term  "[CLS] token with i.e. [PROXY] token" but not just "[PROXY] token"? It is confusing to read.

10. I think the caption in Fig.5 and Fig. 6 should be y-axis (singular).

11. In Sec. 4.4, as a comparison, how many [IMAGE] tokens are there?

12. In Tab. 1, Why compare to only Linear for PascalVOC and only FT for ADE20K? Is using the CLS and Patch tokens as auxiliary inputs for the classifier necessary in the ImageNet experiments? Why is there no "using CLS or Patch tokens" for PascalVOC and ADE20K?

[1] MIMIC: Masked Image Modeling with Image Correspondences. CVPRW 2024.
[2] Learning Vision from Models Rivals Learning Vision from Data. CVPR 2024.
soundness: 3
strengths: 1. The analysis of MIM and CL can be beneficial to the community.
2. Introducing [PROXY] tokens between [CLS] and [MASK] as the solution is simple.
3. Visualization in the experiments highlights the claims of the paper.
summary: This paper first compares the pros and cons of two related but different lines of work: masked image modeling (MIM) and contrastive learning (CL). They then propose SemanticMIM which brings the pros of CL, i.e. suppression, and global representation, etc, into MIM. Experiments show improvement in several tasks.
weaknesses: 1. The presentation is not good. The figures do not help explain the methods.

---

confidence: 3
contribution: 3
initial_rating: 6
presentation: 3
questions: The shortcomings in the experimental section raise concerns about whether this training method can scale to larger models and be applied to a broader range of downstream tasks. If the authors can provide additional experimental results, I would be willing to reconsider and potentially increase the score.
soundness: 3
strengths: The strengths of this paper lie in its innovative integration of Masked Image Modeling (MIM) and Contrastive Learning (CL) within a unified framework, effectively leveraging the advantages of both approaches. Additionally, SemanticMIM excels at capturing both global semantics and local features, enhancing the ability to distinguish specific object semantics. Finally, in addition to quantitative experiments, the paper also includes extensive qualitative analyses and visualizations to demonstrate the effectiveness of the framework.
summary: The paper introduces SemanticMIM, a framework that combines Masked Image Modeling (MIM) and Contrastive Learning (CL) for enhanced visual representation.

Key Contributions:

Theoretical Insights: It analyzes the complementary strengths of MIM and CL, emphasizing their different approaches to semantic modeling—CL focuses on global semantics, while MIM emphasizes local details.

Framework Design: SemanticMIM integrates CL's benefits within the MIM framework using a proxy architecture that combines compression and reconstruction processes into a single learning framework.

Experimental Results: The framework demonstrates significant performance improvements in distinguishing specific object semantics and identifying relevant features, outperforming both MIM and CL in various tasks.

Conclusion: SemanticMIM effectively captures global and spatial information, leading to notable advancements in visual representation for downstream applications.
weaknesses: The paper's limitations include insufficient quantitative experiments, particularly a lack of tests with models of varying sizes across different settings. Additionally, while the paper provides segmentation results for downstream tasks, the promising attention effects raise expectations for object detection performance as well. It would be beneficial for the authors to include more experimental results in the rebuttal stage.

---

confidence: 5
contribution: 2
initial_rating: 5
presentation: 1
questions: Do you think the downstream task performance is good enough to evaluate a self-supervised model? If so, the current MIM methods have achieved very good results and I think the proposed method has NO potential to reach such high results. If not, what metrics is needed do you think to evaluate a pretrained model?
soundness: 3
strengths: 1. The novelty seems good, a very interesting method to combine the MIM and CL together;
2. Many analysis experiments enhance the quality of this paper;
summary: This paper proposes a self-supervised learning method to pretrain vision transformers named SemanticMIM. SemanticMIM tries to take the advantage from both masked image modeling and contrastive learning by leveraging a proxy architecture that customizes interaction between image and mask tokens, bridging these two phases to archieve general visual representation with the property of abundant semantic and positional awareness. I think the novelty of this paper is good. But my presentation is poor and the experiments are so insufficient.
weaknesses: 1.I do not think attention response (figure 1&7&8) can represent the the quality of the learned features. For example, the attention responses of models using the CLIP model as a supervisory signal all appear poor, but their actual performance is often much better.
2.It seems that the authors did not use \citep{} correctly while writing and instead used \cite{}. This resulted in an inconsistent citation format throughout the entire paper.
3.I suggest the authors to provide a comparison on training cost, because the proposed method seems have larger computational cost.
4.Experimental results are insufficient: longer epochs and larger models (L-scale) need to be validated, which is crucial for self-supervised learning. Downstream task results are also needed, such as semantic segmentation and object detection. (This is the biggest concern!)

---

confidence: 3
contribution: 3
initial_rating: 5
presentation: 2
questions: From Fig. 14, it appears that different layer depths yield different types of attention maps. In Fig. 1, are all the displayed attention maps derived from the same layer depth? Providing this clarification will help readers better understand the visual interpretability.
soundness: 2
strengths: 1. The analysis of the fundamental principles underlying CL and MIM is insightful and thought-provoking.

2. The proposed SemanticMIM is well-motivated, which leverages the strengths of both CL and MIM.

3. SemanticMIM improves the performance of two MIM methods when applied using the training scheme introduced in this paper.
summary: This paper proposes SemanticMIM, a framework that integrates the strengths of masked image modeling (MIM) and contrastive learning (CL) to achieve general visual representation learning. Specifically, SemanticMIM leverages a proxy architecture to compress information from image tokens into proxy tokens and then reconstructs masked tokens, thereby combining the semantic awareness of CL with the spatial sensitivity of MIM. As the approach only modifies the encoder architecture, it can be seamlessly integrated into any MIM framework. Extensive experiments further validate the effectiveness of the model and offer interpretability through attention visualization.
weaknesses: 1. Some important details about the training process are missing. For instance, are the [PROXY] tokens supervised with specific targets, similar to the supervision used in CL? Are the [MASK] tokens trained using the same loss function employed in typical MIM frameworks? Clarifying these aspects would enhance the reproducibility and understanding of the proposed approach.

2. The classification of SSL methods into only CL and MIM may not be entirely accurate. Earlier works also introduced a variety of pretext tasks, such as image colorization and rotation prediction, which play an important role in the development of SSL methods. A more comprehensive overview of these earlier approaches can be found in the survey “Self-supervised visual feature learning with deep neural networks: A survey”.

3. The reproduced performance of BEiT and Maskfeat in this paper appears much lower than the original results reported in their respective papers. Could you clarify why the official training schemes were not followed? Additionally, if the official training schemes were applied, how much improvement would SemanticMIM bring to these MIM methods?

4. The citation format in some sections of the text requires correction. For example, “Self-supervised learning (SSL) algorithms Liu et al. (2021); Balestriero et al. (2023) have emerged as …” should be revised to “Self-supervised learning (SSL) algorithms (Liu et al. 2021; Balestriero et al. 2023) have emerged as …” to conform to general academic writing practices.

Meta-review: This paper presents a visual pre-training algorithm that unifies masked image modeling and contrastive learning. It first formulates these two types of pre-training methods using one framework, and then proposes a new pipeline that uses compressed image tokens to guide the model to reconstruct the masked tokens. Although with a smaller number of [PROXY] tokens, the overall framework is **not** essentially different from the vanilla MIM -- note that MIM, with a large masking ratio, can force the model to work on highly-compressed image tokens. Also, the experiments are not strong enough to validate the effectiveness; in particular, experiments on larger backbones and downstream tasks are not complete.

The overall rating of this paper falls on the borderline (5/5/6/6). The reviewers are mostly concerned about the writing (some typos, missing technical details, etc.) and experiments (small models, short training schedules, weaker baselines, etc.). Given this many points to resolve, the AC cannot suggest acceptance this time and suggests the authors to continue improving this work.

Decision: Reject