No Train, all Gain: Self-Supervised Gradients Improve Deep Frozen Representations

Authors: walter  simoncini
spyros  gidaris
andrei  bursuc
yuki m asano
Venue: NeurIPS_cc_2024_Conference
Published: 2024-05-15 15:35:02

Abstract: This paper introduces FUNGI, **F**eatures from **UN**supervised **G**rad**I**ents, a method to enhance the features of transformer encoders by leveraging self-supervised gradients. Our method is simple: given any pretrained model, we first compute gradients from various self-supervised objectives for each input. These gradients are projected to a lower dimension and then concatenated with the model's output embedding. The resulting features are evaluated on k-nearest neighbor classification over 11 datasets from vision, 5 from natural language processing, and 2 from audio. Across backbones spanning various sizes and pretraining strategies, FUNGI features provide consistent performance improvements over the embeddings. We also show that using FUNGI features can benefit linear classification, clustering and image retrieval, and that they significantly improve the retrieval-based in-context scene understanding abilities of pretrained models, for example improving upon DINO by +17% for semantic segmentation - without any training. Code is available at https://github.com/WalterSimoncini/fungivision.

Main paper: 
 introduction: 
 The k-nearest neighbor algorithm (kNN) (Fix, 1985) is a fundamental non-parametric machine learning tool, and can be scaled to datasets with billion of examples thanks to advances in quantization (Jegou et al., 2010; Guo et al., 2020) and efficient GPU implementations (Johnson et al., 2019) . This simple and versatile algorithm has shown potential in multiple applications well before deep neural networks became relevant (Efros & Leung, 1999; Hays & Efros, 2008; Torralba et al., 2008) . Its recent applications include fast and robust image classification with Vision Transformers (Caron et al., 2021; Chen & He, 2021) , unlabeled data selection (Yalniz et al., 2019) , relevant text-retrieval (Lewis et al., 2020) , and visual in-context learning (Balazevic et al., 2024) , where a context of data samples with their annotations (e.g., a semantic segmentation map) are used to make dense predictions.Devising powerful and expressive features for recognition and image understanding has a long history in computer vision. Feature engineering strategies range from simple local features (Lowe, 2004; Dalal & Triggs, 2005; Van De Sande et al., 2009) extracting gradient, boundary or color information, to various mid-level (Boureau et al., 2010) or global pooling (Oliva & Torralba, 2001; Sivic & Zisserman, 2003; Jégou et al., 2010) techniques. It is also possible to couple off-the-shelf pretrained backbones as feature extractors with such pooling strategies (Gong et al., 2014; Kulkarni et al., 2015; Gidaris et al., 2020) to improve performances. While these approaches demonstrate the utility of using a neural network's learned embedding space, they still require specific expertise and tuning for each backbone and task with only limited guidance from the data itself. given a pretrained backbone f θ * and its embeddings, we apply a family of SSL losses, extract their gradients, and project and concatenate them. These new features are used to build a k-nearest neighbor index, which can be used for classification or retrieval.We depart from this line of work and aim to attain strong representations without training and feature engineering, yet still exploiting information cues from data. In particular, we suggest to enhance the neural network's embeddings by incorporating FUNGI (Features from Unsupervised GradIents). FUNGI are obtained from self-supervised loss functions, as these do not require any human annotations and allow for a simple enhancement to embedding-only kNN. The losses are computed on top of pretrained backbones (with randomly initialized linear layers if needed), which permits our method to be "plug-and-play" and benefit from the diverse set of pretraining objectives put forth by the community.We explore gradients from various learning objectives, such as contrastive learning (Chen et al., 2020a) and self-distillation (Caron et al., 2021) thereby integrating complementary information that mitigates the weaknesses of individual losses. The gradients are obtained from late hidden layers, making them computationally cheap. Finally, these are projected to smaller dimensions, and concatenated with the neural network embeddings, to yield new inputs to the classic kNN algorithm.Using kNN with FUNGI can be regarded as a non-parametric transfer learning approach: the gradient information encodes first-order learning signals that are specific to the downstream data, yet no parameters need to be updated. Despite this simplicity, we achieve consistent performance improvements across multiple models and benchmarks.Overall, our main contributions are summarized as follows:• We introduce FUNGI, a novel method that combines neural network features and gradients to enhance representations. • We demonstrate that the gradients from self-supervised losses have predictive abilities and offer complementary information to model embeddings. • We validate the generality and utility of our method by achieving consistent gains across 11 image, 5 text, and 2 audio classification benchmarks, plus 2 in-context image segmentation and 2 image retrieval tasks, utilizing a total of 20 backbones. 
related work: 
 Fast Adaptation There is a broad range of approaches to quickly adapt models to newly specified tasks and data. Inspired by early learning-to-learn work (Hochreiter et al., 2001) , meta-learning methods (Finn et al., 2017; Nichol et al., 2018) learn to initialize the parameters of a learner such that it becomes faster to fine-tune with a small number of gradient steps and data. Alternative approaches leverage external memory modules to store relevant training samples to learn to match query examples (Santoro et al., 2016; Vinyals et al., 2016) , learn to produce and compare class-based prototypes (Snell et al., 2017) or learn to generate the weights of a classifier (Gidaris & Komodakis, 2018) or even of an entire neural network (Bertinetto et al., 2016) from only a few labeled examples. The advent of Vision Transformers (Dosovitskiy et al., 2021) enable new parameter-and dataefficient strategies to adapt pretrained models through visual prompts (Jia et al., 2022) and in-context learning (Zhang et al., 2023) . In contrast to this line of works, our method does not require specialized training and can be applied to any frozen pretrained backbone. FUNGI can also be related to test-time training (Sun et al., 2020; Hardt & Sun, 2024) , where the parameters of a predictive model are updated over test samples with a self-supervised objective to reduce the gap between the training and test distributions. While we also use self-supervised objectives and gradients, our approach does not update model parameters and is not limited to predictive models, as it can be applied to any task that can be solved with retrieval.Self-Supervised Learning Objectives In recent years, self-supervised learning (SSL) has made tremendous progress in computer vision. SSL aims to learn good representations from unlabeled data by leveraging supervision from different signals in the data itself via pretext objectives, thus foregoing human supervision. Models pretrained with self-supervision are subsequently finetuned to downstream tasks of interest with few labeled samples. The crux of SSL is in the pretext learning objective. A wide and diverse collection of pretext objectives have been proposed in the community relying on contrastive learning (Chen et al., 2020a; He et al., 2020; Chen et al., 2020b) , clustering (Caron et al., 2018; Asano et al., 2020; Caron et al., 2020) , self-distillation (Caron et al., 2021; Grill et al., 2020; Chen & He, 2021; Gidaris et al., 2021) , feature (Zhou et al., 2022; Assran et al., 2023) or input reconstruction (He et al., 2022) . We hypothesize that the gradients induced by these objectives encapsulate different information from the input data, and that this information can be combined to produce more information-rich representations. Here, we do not use self-supervision in the usual way, i.e., to pretrain an encoder, but rather focus on pretext objectives and data augmentation strategies to compute representations from a frozen pretrained model.Feature Engineering A long-standing research area for pattern recognition and image understanding before the advent of deep neural networks that brought the paradigm of end-to-end representation learning. In contrast, classic feature extraction methods are devised without labeled data and often from only a few data samples. They range from local features, such as SIFT (Lowe, 2004) , HOG (Dalal & Triggs, 2005) , to global pooling, such as GIST (Oliva & Torralba, 2001) , Bag-of-Visual-Words (Sivic & Zisserman, 2003) , Fisher vectors (Perronnin et al., 2010) , VLAD (Jégou et al., 2010) , selective match kernels (Tolias et al., 2013) , etc. These pooling strategies can be easily plugged to intermediate or output neural network activations (Gong et al., 2014; Kulkarni et al., 2015; Gidaris et al., 2020) , harnessing data-driven learned representations. Other modern examples of feature engineering include Head2Toe (Evci et al., 2022) , which augments the model embeddings using intermediate activations, kNN-prompting (Xu et al., 2023) , which uses the next token probabilities of a language model to perform few shot nearest neighbor classification and LOST (Siméoni et al., 2021) which uses patch features from self-supervised vision transformers for object localization. Closer to our line of work, Wei et al. (2022) shows that kernel regression using the empirical neural tangent kernel (eNTK), which corresponds to the model Jacobian, can achieve a performance similar to fine-tuning in vision, and Mu et al. (2020) shows that features obtained from the Jacobian of the top layers of a convolutional neural network can be used to enhance a linear classifier. In contrast, our method does not require any annotations and is computationally cheaper, as we only compute the gradient for a single layer rather than the full Jacobian.  
gradients as features: 
 Gradients encode information on how the weights of a neural network should change to solve a given task. Thus, they contain information about the current state of the network and its relation to the data point(s) used to compute it. Therefore, we hypothesize that features from self-supervised gradients should perform better than the embeddings, as they are adapted to the dataset at hand. Empirically, the second row in Figure 2 shows this to be accurate, e.g., gradients from a SimCLR loss improve the accuracy of k-nearest neighbor classification by 10.1% on Flowers102.If we plot the per-class accuracy distribution as in Figure 3 , we notice that gradient features encode different information depending on the loss and that they can perform significantly worse on some classes, possibly because they are estimated using a single data point, and are thus dependent on the local loss curvature. These findings suggest that the information in embeddings and gradient features could be complementary. We show that this holds in the second row of Figure 2 , as feature pairs perform better. Moreover, the first row of the figure suggests that more diverse feature pairs, as measured via their centered kernel alignment (CKA) (Kornblith et al., 2019) score, lead to better overall performance. 
method: 
 Our method, FUNGI, enhances k-nearest neighbor search by incorporating features from unsupervised gradients. We extract gradients from self-supervised loss functions, project them to smaller dimensions, and concatenate them with neural network embeddings. The extraction of self-supervised gradients is illustrated in Figure 4 , while Figure 1 shows how FUNGI features are constructed.Definitions Throughout this section, we define L 2 normalization as z ′ = z/||z|| 2 , a vision backbone as f , a linear projection head as h and vectorization as vec(•).Gradients Extraction. Given an arbitrary vision backbone f , in our case a vision transformer (ViT) (Dosovitskiy et al., 2021) , we attach a randomly initialized linear projection head h and obtain a latent representation z = h(f ′ (x)) of the input images, which we use to compute the loss for one of our self-supervised objectives. We then run backpropagation and extract the gradients with respect to the weights and biases of an arbitrary hidden linear layer within f . Unless specified otherwise, we use the attention output projection of the last transformer block as our gradient's source.From Gradients to Retrieval-Friendly Features. Gradients are high dimensional and thus impractical for nearest-neighbor retrieval due to speed and storage considerations and the curse of dimensionality. To tackle these issues, we downsample the gradients to the dimensionality of original model embeddings d using the binary random projections method introduced by Achlioptas (2003) .For this, we first vectorize the gradients by flattening them to a m-dimensional vector and then multiply them by a matrix R ∈ {-1, 1} d,m whose entries are the realizations of a Bernoulli random variable with p = 0.5. The gradient g β with respect to a loss L β is then defined asEQUATIONCombining with Embeddings. To produce our FUNGI features ϕ, we concatenate one or more gradients to the model embeddings. As gradient magnitudes can vary widely across losses, and we want gradients to be equally considered as the embeddings, we L 2 -normalize each gradient, as well the embeddings and computeEQUATIONwhere cat denotes concatenation. Finally, we reduce the dimensionality of these combined features via PCA to a d-dimensional vector. This allows the combination of multiple losses at iso-storage cost.Our final FUNGI features for a sample x are thus obtained as:EQUATION4.2 Self-Supervised ObjectivesWe consider losses representing three families of self-supervised objectives: DINO (Caron et al., 2021) , SimCLR (Chen et al., 2020a ) and a KL-divergence based loss inspired by the out-ofdistribution detection literature (Huang et al., 2021) . In this section we briefly describe the objectives and our adjustments to them, and in Appendix B.6, we also briefly discuss clustering and masked image modeling-based losses.DINO. DINO is a distillation and implicit clustering-based learning method. We use the standard DINO loss, which, given an image, enforces global and local crop correspondence between teacher and student models using a cross-entropy loss. In our case, both models share the same parameters, but have independent heads h s and h t for student and teacher respectively, thus we havez i = h i (f ′ (x)) , i ∈ {s, t}.The DINO objective can be expressed as:EQUATIONSimCLR. SimCLR is a noise-contrastive method. Given a batch of images, SimCLR generates two views for each image and aims to minimize the distance between views belonging to the same image and maximize their distance to all other views. Instead, we generate a set of 49 overlapping patches for each image, which we call the positive set. This set is then contrasted against a fixed comparison batch of 49 × 256 negative examples. Our objective is the expectation of the pair-wise InfoNCE (Oord et al., 2018) loss for each pair of positive views. If we define the positive set of latent view representations as Z, wherez i ∈ Z = h ′ (f (x i ))for a view x i , the comparison batch size as N and the temperature as τ , the L SimCLR objective is then defined as:EQUATIONKL Divergence. The KL objective is calculated as the KL divergence between the softmaxed logits of the latents and a uniform distribution U:EQUATION)We hypothesize two reasons as for why this loss produces predictive gradients: first, it receives a non-augmented image, with a higher signal-to-noise ratio compared to other objectives, and second, if we assume that similar images (e.g., the ones that belong to the same class) produce similar activations, then maximizing their entropy by forcing the output distribution to match an uniform should produce similar intra-class gradients and help separability. This hypothesis is supported by the fact that while the KL gradients are discriminative, they have chance performance in other tasks, such as in-context scene understanding. label using an attention mechanism. Images are first resized to 512 × 512, and then encoded as a set of 32 2 = 1024 patch features using a ViT with patch size 16.We enhance the patch features using SimCLR gradients, obtained by contrasting the input patch tokens against their nearest neighbors from a support index built with ScaNN (Guo et al., 2020) . We use the reproduction of this evaluation protocol by Pariza et al. (2024) to run our experiments.5 Experiments In this section, we evaluate the performance of FUNGI in k-nearest neighbor image, text and audio classification and retrieval-based in-context scene understanding. Further experiments, including image retrieval, clustering and linear probing, are provided in Appendix B. 
image classification: 
 Following Caron et al. (2021) , we evaluate our FUNGI features using the task of kNN classification. To show the generalizability of our method, we evaluate our features across ViT backbones (Dosovitskiy et al., 2021) with varying model sizes and pretraining strategies, including both supervised and self-supervised methods.We conduct our experiments on 11 diverse downstream datasets, described in Appendix D. Unless otherwise specified, we report the average accuracy across these datasets. We evaluate our features using the kNN implementation of scikit-learn (Pedregosa Our results, presented in Figure 6 , show that FUNGI consistently improves the kNN performance of all ViT models, regardless of model size or pretraining strategy, both for the full dataset and in few shot scenarios. We further investigate data-efficient settings in Figure 5 , where FUNGI shows a significant improvement when 3 to 6 shots are used, highlighting the potential of FUNGI in low-data regimes.In Table 1 , we show that, with some exceptions, FUNGI provides consistent improvements across datasets for two AugReg (Steiner et al., 2022) ViT-B/16 backbones, pretrained on IN1K and IN21K, with FUNGI providing better results on the former. We further discuss these results in Section 6.Lastly, in Table 2 we show that performance improves as more gradients from different self-supervised objectives are used.In this section, we assess the effectiveness of our approach in the task of retrieval-based semantic segmentation on Pascal VOC 2012 (Everingham et al., 2010) and ADE20K (Zhou et al., 2019, Table 4 : Data-efficient semantic segmentation. mIoU scores for data-efficient retrieval-based semantic segmentation on Pascal VOC 2012 and ADE20K, using DINO backbones and their FUNGI features and embeddings. We also compare FUNGI to end-to-end fine-tuning and find our method to perform best for VOC. Results from Balazevic et al. (2024) 23.6 ↓2.0 29.1 ↓0.6 6.1 ↑0.9 32.0 ↑2.0 24.2 ↓1.7 74.8 ↑3.0 41.0 ↑3.6 24.4 ↑1.0 9.9 ↑1.5 2017). We use the trainaug and train splits to build the memory banks for Pascal VOC and ADE20K, respectively, and report the mean intersection over union (mIoU) on the validation set.We apply FUNGI to DINO ViT-S/16 and ViT-B/16 models. Our results, presented in Table 3 and Table 7 , demonstrate that FUNGI significantly enhances DINO's performance across all memory bank sizes, with the most substantial improvements observed in smaller memory banks for Pascal VOC. Qualitatively, FUNGI produces sharper and more complete segmentation masks, as shown in Figure 7 . Notably, the DINO ViT-B/16 model, when enhanced with our FUNGI approach, achieves competitive results against the current state-of-the-art HummingBird model (Balazevic et al., 2024) , with a difference of only 3.5% on Pascal VOC and 3.1% on ADE20K, without any training. This is a particularly promising result, as HummingBird employs a self-supervised pretraining strategy that is specialized for retrieval-based dense prediction tasks, which are the focus of our evaluation in this study.In addition, we evaluate the efficacy of FUNGI in a data-efficient setup, and report the results in Table 4 . Our findings indicate that our method outperforms DINO in this scenario, even when compared to end-to-end fine-tuning of DINO on the downstream task for Pascal VOC.Natural language. We evaluate FUNGI in the text domain using five datasets, described in Appendix D, and two transformer language models: BERT base uncased (Devlin et al., 2019) and T5-small (Raffel et al., 2020) . We use the L KL and L SimCLR losses and obtain the SimCLR views by randomly deleting words with a 10% probability. The results are presented in Table 5 and show that FUNGI achieves improvements in the text domain. However, SimCLR gradients struggle with some datasets. Different data augmentation strategies, such as back-translation (Sennrich et al., 2016) , or language-specific self-supervised losses, e.g., masked language modeling (Devlin et al., 2019) , may yield more discriminative gradients. We leave this investigation for future work. Furthermore, in Appendix B.5, we investigate the potential of FUNGI in language in-context learning.Audio. We demonstrate gains for the audio modality in Table 12 , where we improve the ESC-50 kNN classification accuracy from 42.8% to 47.0% and SpeechCommands from 27.4% to 29.9% with an SSAST backbone (Gong et al., 2022) . Further details are provided in Appendix B.2. Projection head. To compute our self-supervised losses, we first L 2 -normalize the model embeddings (except for SimCLR) and then project them using a randomly initialized linear head. We motivate this choice empirically by ablating these components, and the results in Table 6 show that this configuration produces the most predictive gradients for ImageNet-100. Gradients source layer. Throughout the paper, we extract gradients from the self-attention output projection of the last transformer block. Intuitively, deeper layers provide more predictive features, and thus, their gradient should display the same behavior. This assumption is confirmed by our results in Figure 8 , where, for all losses, deeper layers consistently produce more predictive gradients.Regarding the choice of layer within a transformer block, for shallower blocks, the second MLP layer is significantly more predictive, but the performance gap becomes insignificant as we move towards deeper blocks, favoring (by a small margin) the attention output projection, which is also more memory efficient, as it has fewer parameters compared to other layers. 
discussion and conclusion: 
 Broader impact. Our method improves the features used for the kNN algorithm. As such, it is a fundamental contribution to Machine Learning. Given the ubiquitous use of kNN, our method could have positive consequences, such as improving reliability and factuality in Retrieval Augmented Generation (RAG) systems, where Language Models are grounded in retrieved pieces of text before generating an answer. We do not foresee any direct negative consequence caused by our method.Impact of pretraining dataset. Our method works with various backbones, model sizes, and pretraining strategies. However, we have observed that the benefits diminish as the size of the pretraining dataset increases: in Table 1 , FUNGI provides a smaller relative improvements on a backbone pretrained with IN21K compared to one pretrained on IN1K, and similarly, in Table 16 the relative improvement over EVA-CLIP (Sun et al., 2023) is smaller compared to the improvement over CLIP (Radford et al., 2021) , as they are pretrained on 2B and 400M text-image pairs respectively.Computational efficiency. Computing FUNGI features introduces an overhead, which we measure in Table 27 by comparing the throughput of a DeIT ViT-B/16 when extracting gradients and embeddings. The DINO and SimCLR losses have the largest overhead, as they forward 12 and 49 views per image, respectively. As shown in Appendix C.1, this number can be reduced, at a performance cost. However, thanks to our dimensionality reduction, the speed of kNN retrieval is not impacted. 
conclusion: 
 We have shown that gradients from self-supervised objectives have predictive abilities and encode complementary information to the model embeddings. Building on those findings, we introduced FUNGI , which effectively combines embeddings and gradients into powerful features for retrievalbased tasks. Specifically, we have shown that FUNGI enhance the performance of kNN-based image and text classification across models, pretraining strategies, and downstream datasets, both for full dataset and few shot setups. Moreover, we have shown that FUNGI significantly boost the performance of DINO features for retrieval-based semantic segmentation tasks.  
 
 Appendix: Algorithm 1 provides pytorch-style pseudocode for the computation of L KL , the gradient extraction, and the computation of FUNGI features (without PCA).Algorithm 1 PyTorch pseudocode for the KL FUNGI features.# model, head, proj: the vision backbone, head and the random projection used to downsample gradients proj = (torch.rand(feat_dim, grad_dim) -0.5) > 0 uniform = torch.ones(feat_dim) / feat_dim for x in dataset: # Extract the feature and its projection y = model(x) z = head(y) kl_div(log_softmax(z), softmax(uniform)).backward() # Calculate the loss and backpropagate layer = model.blocks.11.attn.proj # Select the target layer # Extract and project the gradients gradients = torch.cat([layer.weight.grad, layer.bias.grad.unsqueeze(dim=-1)], dim=-1).view(-1) gradients = proj @ gradients.view(-1) feature = torch.cat([normalize(y), normalize(gradients)], dim=-1) # Build the final featureIn this section we first illustrate additional results that solidify the findings discussed in the main paper, including the evaluation of FUNGI in image retrieval, k-nearest neighbor audio classification, linear classification and clustering and a brief investigation of the performance of gradients from clustering and masked image modeling self-supervised objectives.In Table 8 , we report the of embeddings and FUNGI features for some additional backbones, including CLIP and EVA-CLIP models, for which, as explained in the main text, we experience diminishing returns as the pretraining dataset size grows. Moreover, for both models, the SimCLR loss does not produce predictive gradients, which we hypothesize is due to models being saturated to a contrastive loss, as they use a similar objective for pretraining.In Table 10 , we report the mean accuracy and one standard deviation (computed via numpy.std) across three seeds for a subset of our datasets, using a DeIT ViT-B/16 backbone, showing that the performance improvements of FUNGI are consistent across seeds.In Figure 11 we evaluate the effectiveness of FUNGI across different ViT model sizes. The findings show that FUNGI improves the results for all three ViT models (ViT-S, ViT-B, and ViT-L), with the most significant improvements observed in the ViT-B model. In Table 9 , we provide further evidence for the scalability of FUNGI by evaluating it on several ViT-L and ViT-H backbones.In Table 7 , we report the performance of FUNGI for in-context retrieval-based semantic segmentation on ADE20K, and show that our method outperforms DINO across all memory bank sizes and is competitive against HummingBird. (Radford et al., 2021; Sun et al., 2023) , AugReg (Steiner et al., 2022) , DeIT III (Touvron et al., 2022) and masked autoencoder (He et al., 2022) models. "K", "D" and "S" stand for KL, DINO and SimCLR, respectively. We evaluate the performance of FUNGI features in image retrieval using the revisited (Radenović et al., 2018) Oxford (Philbin et al., 2007) and Paris (Philbin et al., 2008) landmarks datasets. We report the mean average precision (mAP) for both the medium (M) and hard (H) splits.For this task, we use FUNGI features built with DINO and KL gradients, as the SimCLR gradients did not result in good retrieval performance. The results displayed in Table 11 show that FUNGI features improve the retrieval abilities of all backbones, except for DINOv2. Our method is particularly effective when applied on CLIP backbones: on the Paris hard split, we improve by 12.4% and 7.2% for CLIP and EVA-CLIP, respectively. We evaluate FUNGI on the audio modality using SSAST (Gong et al., 2021 (Gong et al., , 2022)) , a self-supervised audio spectrogram transformer trained for audio and speech classification, as the backbone. We construct FUNGI features using KL and SimCLR gradients, and test their performance in k-nearest neighbor classification on ESC 50 (Piczak, 2015) and SpeechCommands V2 (Warden, 2018) .We use the same formulation as in the vision experiments for the L KL and L SimCLR objectives. However, for the latter, we obtain 16 views of the same clip by adding uniform noise following Gong et al. (2022) . If we define the filter bank of an audio clip as c ∈ R h,w , the noise-augmented clip ĉ is computed as:ĉ = c + x 1 • x 2 10 x 1 ∼ U (0, 1) h,w x 2 ∼ U (0, 1). (7)Finally, ĉ is shifted by a factor sampled from a discrete uniform distribution U (-10, 10). The complete list of hyperparameters used for the audio classification experiments is reported in Table 13 .The results are reported in Table 12 , and show that FUNGI features built using KL gradients yield promising results, improving by up to 4.2% on the baseline. On the other hand, using SimCLR gradients does not consistently yield improvements. It rather often causes a performance drop when combined with KL gradients. As with text classification, further research is needed to determine the optimal self-supervised objectives and data augmentation to extract predictive gradients.We evaluate FUNGI features in logistic regression, using the implementation from the cyanure library (Mairal, 2019) . We train each classifier for a maximum of 300 epochs (30 in the case of ImageNet-1K) using L 2 regularization. For each dataset and feature combination (i.e., embeddings, embeddings + ∇ KL , etc.), we pick the best regularization parameter between 5 linearly spaced values in the interval [5 × 10 -6 , 5 × 10 -4 ] using the validation set. For datasets without a validation set, we generate one using an 80/20 stratified split. The final model is trained using the entire training dataset.We report the results in Table 15 and Table 16 and find that, in linear classification, FUNGI features are most effective for backbones pretrained using a supervised objective. In contrast, self-supervised backbones do not benefit as much. This is especially evident for DINO and DINOv2, whereTable 11: FUNGI improves image retrieval. average precision (mAP) of embeddings and FUNGI for retrieval on the Paris (Philbin et al., 2008) and Oxford (Philbin et al., 2007) landmarks datasets, for both medium (M) and hard (H) splits. "K" and "D" stand for KL and DINO, respectively. FUNGI often yields worse results, especially in a few shot scenarios. Contrary to the k-nearest neighbor classification results, the best feature combination is backbone specific, and in Figure 9 , we show that significant performance improvements can be achieved by picking the best feature combination for each backbone.We evaluate the performance of FUNGI features built with KL and DINO gradients in k-means clustering (Lloyd, 1982) of image features using faiss (Johnson et al., 2019; Douze et al., 2024) . Given a dataset with C classes, we compute C clusters via k-means and match clusters to classes using the Hungarian algorithm (Kuhn, 1955) . We then measure the average overlap between clusters and classes. The results in Table 14 show that, on average, FUNGI features built with KL and DINO gradients improve the overlap between clusters and classes. In particular, FUNGI can improve the clustering performance by up to 15.8% on Oxford-IIT Pets for a CLIP ViT-L/14 backbone.Liu et al. ( 2022) has shown that selecting examples for in-context learning using retrieval outperforms a random baseline, and that using encoders fine-tuned on a task similar to the target one further improves performance. Thus, we hypothesize that using FUNGI features to retrieve in-context examples can improve performance, as they contain an adaptation signal to the task at hand. We test this hypothesis by measuring the in-context classification performance of GPT 4o mini (Achiam et al., 2023) using examples retrieved either using embeddings or FUNGI features built with KL and 14: FUNGI improves clustering. Overlap between classes and clusters found via k-means clustering of embeddings and FUNGI features. "K" and "D" stand for KL and DINO respectively. Full (Steiner et al., 2022) .A R IN 1 K V iT -S /1 6 D e IT V iT -B /3 2 A R IN 2 1 K V iT -S /1 6 A R IN 2 1 K V iT -B /1 6 D e IT -I II V iT -B /1 6 M o C o v 3 V iT -B /1 6 D e IT V iT -B /1 6 D IN O V iT -B /1 6 C L IP V iT -B /1 6 A R IN 2 1 K V iT -L /1 6 E V A C L IP V iT -B /1 6 D IN O v 2 V iT -B /Dataset A R IN 1 K V iT -S /1 6 D e IT V iT -B /3 2 A R IN 2 1 K V iT -S /1 6 A R IN 2 1 K V iT -B /1 6 D e IT -I II V iT -B /1 6 M o C o v 3 V iT -B /1 6 D e IT V iT -B /1 6 D IN O V iT -B /1 6 C L IP V iT -B /1 6 A R IN 2 1 K V iT -L /1 6 E V A C L IP V iT -B /1 6 D IN O v 2 V iT -B /SimCLR gradients using a BERT backbone. We retrieve the top 20 most similar training examples for each test sample and ask the model to predict its label using a prompt template similar to the one shown in Listing 1. For a fair evaluation, we set the model temperature to 0. The results listed in Table 17 show that examples retrieved using FUNGI features improve the in-context learning accuracy by up to 2.5% on banking-77.You have to annotate banking -related queries with an appropriate intent . You must choose a single class in the following comma -separated list :{ list of possible labels , comma -separated } You must reply only with the class name , nothing more . Here ' s some examples :{( text , label ) pairs from the training set }The query sample is : { query text } ¦ ¥ Listing 1: The prompt used for the in-context learning evaluation of embeddings and FUNGI features on banking-77 using a GPT 4o mini backbone. The labels are given as strings, e.g. exchange_rate.In this section, we study the performance of gradients obtained by two additional self-supervised objectives, DeepCluster (Caron et al., 2018) and iBOT (Zhou et al., 2022) in k-nearest neighbor classification on ImageNet-100 using a DeIT ViT-B/16 backbone. DeepCluster is a self-distillation and explicit clustering-based self-supervised method that alternates between clustering image features and training a model to predict cluster assignments. iBOT is an extension of DINO that combines image and patch-level objectives, the latter implemented as a latent-space masked image modeling (MIM) objective, where a learnable patch token replaces a subset of patches, and the model must reconstruct them. & Johnson (1984) , which states that for a set of N d-dimensional points and a projection subspace of dimension k ≥ k 0 = O(ϵ -2 log(N )) there exist a mapping f : R d → R k that preserves euclidean distances with a distortion of at most ϵ ± 1. This mapping can be either implemented as a Gaussian, binary (Achlioptas, 2003) or sparse (Li et al., 2006) projection. Our method uses a binary projection, as it's more memory-efficient than a Gaussian matrix, and in Table 19 , we compare its performance to the other initializations. The results show that the initialization has little impact on downstream performance, favoring binary projections by a small margin.Table 19 : The random projection initialization has little impact on performance. Comparison of the downstream accuracy of FUNGI features built with gradients projected using matrices with different initializations. We report the mean and one standard deviation measured across three runs using the Flowers102 dataset and a DeIT ViT-B/16 backbone. No further dimensionality reduction was applied to the concatenated features. Binary Gaussian Sparse Embeddings 56.9 56.9 56.9 + K 59.7 ± 0.4 60.2 ± 0.2 60.0 ± 0.1 + K + D 63.5 ± 0.1 63.2 ± 0.5 63.1 ± 0.2 + K + D + S 69.2 ± 0.6 69.0 ± 0.7 68.9 ± 0.9 PCA. We use Principal Component Analysis (PCA) to combine data from multiple losses at an iso-storage and retrieval speed cost. Given a dataset of FUNGI features, we fit the PCA on the training split and use it to transform training and test splits. Table 20 lists the PCA dimensionalities used for each model architecture and shows that they do not cause a decrease in performance but rather provide a minor improvement on average. Moreover, we compare PCA against binary, Gaussian, and sparse random projections in Table 21 and find that all random projection-based methods result in a drop in accuracy compared to the original features, while PCA consistently improves performance. For the evaluation of the in-context scene understanding abilities of FUNGI features we closely replicate the setup described by Balazevic et al. (2024) for both the full and few shot setups, with two minor exceptions: (1) we use a single augmentation epoch for the full dataset evaluation and (2) we use an anisotropic quantization threshold of 0.2 for the nearest neighbor index, as this parameter was not specified in the paper. The full set of parameters for the evaluation, loss computation and data augmentation is reported in Table 23 . As for data augmentation, we use the same policy of Balazevic et al. (2024) , and apply each augmentation independently.In order to construct FUNGI features for this task, we implement a SimCLR loss that contrasts patch tokens from an input image to their nearest neighbors retrieved from a supporting memory bank. In practice, we:• Construct a memory bank of image patches of the same size as the one used for evaluation and its nearest neighbor index with ScaNN (Guo et al., 2020) following the procedure by Balazevic et al. (2024) . We call this our support index.• Then, for each image, we:1. Resize it to 512 × 512, compute its [CLS] and patch tokens and project them with a linear head. Excluding the [CLS] token, each image is mapped to 32 2 = 1024 features, as all our backbones use patches of size 16. 2. For each token, retrieve its two nearest neighbors from the support index and randomly drop 50% of them. 3. Compute the SimCLR loss, where the patch tokens constitute the positive set and the neighbors the negative batch. This allows us to compute a per-patch gradient. 4. Drop the [CLS] token, as it does not correspond to a real image patch. 5. Construct FUNGI features as in Equation 8, where f (x) maps an image to patches of dimension d, L 2 normalization is defined as z ′ = z/||z|| 2 and cat indicates concatenation.EQUATIONThe parameters used to extract gradients from text encoders for L KL and L SimCLR are shown in Table 24 . The gradient source layer is always the attention output projection of the last transformer encoder block. We use the same parameters across backbones. No data augmentation is used for the L KL , while for L SimCLR the views are obtained by randomly deleting words independently, where each word has a 10% probability of being deleted. We investigate the performance of our gradient-enhanced features on 11 image classification datasets, namely CIFAR 10 and CIFAR 100 (Krizhevsky et al., 2009) , Oxford Flowers 102 (Nilsback & Zisserman, 2008) , Food101 (Bossard et al., 2014) , ImageNet-1K (Russakovsky et al., 2015) , FGVC Aircraft (Maji et al., 2013 ), CUB 200-2011 (Wah et al., 2011 ), Oxford-IIT Pets (Parkhi et al., 2012) , Stanford Cars (Krause et al., 2013) , DTD Textures (Cimpoi et al., 2014) and EuroSAT (Helber et al., 2019) , 5 text classification datasets: TREC (Li & Roth, 2002) in its coarse version, banking-77 (Casanueva et al., 2020) , Stanford Sentiment Treebank (SST) (Socher et al., 2013) in its fine-grained version, AG news (Zhang et al., 2015; Gulli, 2005) and tweet eval (emoji) (Barbieri et al., 2018 (Barbieri et al., , 2020) ) and 2 audio classification datasets: ESC 50 (Piczak, 2015), an environmental sound classification dataset, and SpeechCommands V2 (Warden, 2018) , a keyword spotting task, where the goal is to classify utterances into a predefined set of words. The datasets, their license and citations are also listed in Table 25 .We follow the evaluation protocol for each individual dataset and report the top-1 accuracy for CIFAR 10 and 100, Food101, ImageNet-1K, Stanford Cars, EuroSAT, DTD Textures, CUB 200-2011, TREC, banking-77, SST, AG news, tweet eval (emoji), ESC 50 and SpeechCommands V2, and the mean-per-class accuracy for Flowers102, FGVC Aircraft and Oxford-IIT Pets.use the default splits defined by torchvision or the dataset authors where possible. As EuroSAT does not explicitly define a test split, we use an 80/20 stratified split as indicated by the dataset paper. We always report metrics on the test splits, with the exception of ImageNet, for which we use the validation split. We evaluate FUNGI features across several architectures, pretraining strategies and model sizes. These are listed in Table 26 , alongside their license, data type and citation.The gradient features were extracted using a machine with a single NVIDIA A100 GPU with 40GB of VRAM. Considering the inference times listed in Table 27 , replicating the k-nearest neighbor image classification results would require approximately 27 GPU hours per backbone using float16, which we use throughout all our experiments. As we evaluate our method across 17 vision backbones, reproducing these results would require 459 GPU hours. As for the text and audio classification experiments, they require around 3 GPU hours per backbone, for a total of 9 hours. The extracted gradient features were reused for the linear probing and clustering experiments, the former requiring 168 hours on a machine with a single AMD EPYC 7H12 CPU and the latter requiring 18 hours on a machine with a single NVIDIA A100 GPU with 40GB of VRAM. Finally, additional experiments such as image retrieval, in-context learning, and ablation studies required approximately 84 hours, while the preliminary experiments for this paper required a negligible amount of compute. 


Decision: Overall, the paper is well-received with three positive reviews and one borderline reject. The reviewers commend the paper's clarity, novelty, and effectiveness. While some concerns were raised regarding missing backbones, scalability, and theoretical explanations, the paper's strengths outweigh these weaknesses. The authors' ability to demonstrate the effectiveness of their proposed method across various datasets and pre-trained models is particularly noteworthy. The paper's contribution of combining self-supervised gradients with pre-trained embeddings is novel and promising.

Reviews: review: paper_summary: paper_summary: The paper introduces an approach to augment the feature representations from ViTs, by utilizing the gradients from self-supervised losses. The gradients from the attention output projection of the last transformer block is extracted and projected into the output embedding space using random-projections and PCA to compute FUNGI. Exhaustive experimental evaluation across vision and NLP datasets brings out the efficacy of the approach.
strength_weakness: strength_weakness: - The method to generate features from unsupervised gradients seems very empirical. Any theoretical backing for the good results would further improve the paper.
questions: questions: - Intuitively, the proposed approach "encodes first-order learning signals that are specific to the downstream data" (line 46). If we use task specific loss functions, instead of self-supervised loss, would it further help with the adaptation of the latent representation towards the downstream task?
- How much is the method dependent on the PCA that is performed to reduce the dimensionality (line 141)? Would there be any other alternative to try?
- FUNGI has been found effective is augmenting features used for k-NN based classification and scene understanding task. Can FUNGI features be consumed by downstream discriminative classifiers that are trained with softmax?
- Would be good to clarify whether the reported numbers are the mean of multiple runs.
limitations: limitations: NA
paper_summary: paper_summary: - The draft introduces a feature enhancement technique called FUNGI (Features from Unsupervised GradIents) for vision transformers. - 
- The core idea is to leverage the un/self-supervised loss gradients at an arbitrary hidden layer within a vision backbone (the default option being the attention output projection of the last transformer block) to enhance the feature embeddings
- These gradients, along with the pre-trained embeddings, are shown to achieve higher accuracy in kNN classification across various datasets and transformer backbones.
- Comprehensive experimentation evaluated this technique in three activities (image classification, in-context scene understanding, and text classification). Consistent gains in accuracy are reported across model backbones, tasks/datasets, learning scenarios, etc.
strength_weakness: strength_weakness: 1. Although complementary information is extracted as gradients, it is computationally demanding - it requires one (partial) backpropagation for each self-supervision objective, total backpropagation operations are linear with respect to the number of objectives, the added linear projection head (h), and finally, the dimensionality reduction to match the dimension of the embedding. One may opine that the additional cost is not worth performance gains (poor returns). Overall, the gains may not be significant to be deployed in practice.

2. The draft provides no sound reasoning regarding the performance enhancement resulting from the self-supervised gradients. Section 3 (figures 2 & 3) empirically proves that these gradients complement the embeddings but doesn't discuss how/why.
questions: questions: 1. It would be interesting to understand (if not already) the role of the pre-trained embedding. In other words, can a half-trained or untrained (random) embedding also extract discriminative information from the self-supervised objectives similar to the pre-trained one? Authors may clarify this.

2. Authors may clarify the second weakness mentioned in the above section.
limitations: limitations: The authors addressed the limitations and potential societal impact of the proposed work.
paper_summary: paper_summary: The paper proposes a simple method named FUNGI - Features from Unsupervised Gradients, to improve the representations of Vision Transformers (ViTs). Specifically, FUNGI uses gradients from self-supervised objectives to augment the embeddings from pre-trained models. FUNGI involves three straightforward steps - (i) compute gradients at a specific layer for selected self-supervised objectives (ii) project the gradients to a lower dimension (iii) concatenate these projected features with the model’s embeddings for kNN-based classification. Extensive experiments across various datasets, pre-trained models, and tasks demonstrate the effectiveness of the proposed approach.
strength_weakness: strength_weakness: - **Missing backbones**: While the authors have presented results on a comprehensive list of backbones, a few recent backbones are missing, which are listed below:
    - Touvron, Hugo, Matthieu Cord, and Hervé Jégou. "Deit iii: Revenge of the vit." ECCV 2022.
    - Vasu, Pavan Kumar Anasosalu, et al. "Mobileclip: Fast image-text models through multi-modal reinforced training." CVPR 2024.

- **Scalability**: There is no discussion on how FUNGI scales with larger ViT models. All the analyses are performed with ViT-B and ViT-S. The authors should also demonstrate the scalability of FUNGI with larger ViT models across the various pre-training schemes that they have presented results on for ViT-B and ViT-S.
questions: questions: 1. Does FUNGI also work for CNNs and CNN-ViT hybrid architectures? For example, MobileCLIP mentioned above consists of convolutional layers and attention-based layers. Would FUNGI work for CNNs such as CLIP ResNet-50 and CNN-ViT hybrids such as MobileCLIP?

2. Since FUNGI is a generic gradient-based method, does it extend beyond classification tasks? Would FUNGI work for generative models such as LLMs, VLMs such as Llava, and BLIP? The application of FUNGI to any such model would greatly improve the impact of the work.
limitations: limitations: The authors have adequately addressed the limitations of the work.
paper_summary: paper_summary: This paper presents an unsupervised method to enhance the representations of pretrained models. The authors observe that gradient features from various self-supervised objectives are helpful to enhance k-nearest neighbor (KNN) retrieval. The proposed method, FUNGI, combines the embeddings of a pretrained model with gradients from different self-supervised objectives, followed with dimensionality reduction from PCA. Experiments on Image classification, semantic segmentation and text classification show the effectiveness of proposed algorithm.
strength_weakness: strength_weakness: 1. My biggest concern is that the evaluation of proposed method is limited to nearest neighbor retrieval (though I agree that this task is important). As a method of feature engineering, it'd be good to test the performance of (few-shot) linear prob or K-Means clustering.

2. Lack of analysis on random projection. For example, [6] uses random Gaussian matrix to project the gradient features to low-dim and shows that it perseves inner-product with high probability. In FUNGI, the projection matrix is sampled in {-1, 1} by Bernoulli random variables. What properties would it have?

3. Some related works are not covered. There've been a number of works using gradient as features for downstream tasks, for example [1-3]. It'd be good to metion them and discuss the intuition why gradient could be used as features for KNN retrieval. The same also holds for the analysis on self-supervised learning objectives, for example [6].

[1] Gradients as Features for Deep Representation Learning, ICLR 2020.

[2] More than a toy: Random matrix models predict how real-world neural representations generalize. ICML 2022. 

[3] Head2Toe: Utilizing Intermediate Representations for Better Transfer Learning. ICML 2022.

[4] A Kernel-Based View of Language Model Fine-Tuning. ICML 2023.

[5] Trak: Attributing model behavior at scale. ICML 2023.

[6] Learning by Reconstruction Produces Uninformative Features For Perception. 2024
questions: questions: 1. What's the dimension of the gradient feature? What's the time cost of random projection and PCA?

2. What's the advantage of random projection with matrix sampled from {-1, 1}, compared to random Gaussian matrix? 

3. For text classification, nearest neightbors are used to select examples for in-context learning [1]. Would FUNGI be helpful in this process?


[1] What makes good in-context examples for gpt-3? ACL 2022.
limitations: limitations: The author have discussed some of the limtations in the paper. For others, please refer to "Weakness"

Comments: title: Acknowledgement
comment: We’re thankful to the reviewers for their comments. We’re happy to answer any further questions or clarify our responses as needed.
Thank you for your response and for updating the rating.

**About the choice of gradients:** correct. For our experiments we use the full gradient with respect to the weights and bias of a single layer, as this is simpler (implementation-wise) and we expect this to be more stable overall, compared to picking a subset of the gradient matrix. While picking only a subset of the gradient is an interesting direction, we did not investigate it thoroughly. Nonetheless, we can make the following observations:

- As shown in Table 30, removing the bias gradient may lead to even better performance.
- As shown in Table 31, for the `qkv` layer we found that using the `v` gradients alone results in better performance compared to the full `qkv` matrix and its other components.

Combining gradients from multiple layers is an interesting idea, thank you. We ran a small experiment and from the results displayed in Table 32, it may lead to better performances, but this is not always the case.

Both ideas require further investigation and evaluation to make any concrete claims.

|                           | Textures | Flowers102 |
| ------------------------- | -------- | ---------- |
| Weight Gradients w/o Bias | 59.4     | 61.0       |
| Weight Gradients w/ Bias  | 59.0     | 60.5       |

_**Table 30. Removing the bias gradient improves performance:** comparison of the downstream accuracy of FUNGI features built with weight only gradients or weight and bias gradients on two datasets using an AugReg IN1K ViT-B/16 backbone._

|     | Textures | Flowers102 |
| --- | -------- | ---------- |
| Q   | 56.7     | 52.0       |
| K   | 55.2     | 52.0       |
| V   | 59.0     | 61.2       |
| QKV | 58.0     | 58.3       |

_**Table 31. The `v` of the `qkv` gradients has the best performance, and can even improve over `attn.proj` (Table 30):** comparison of the downstream accuracy of FUNGI features built with the full `qkv` gradients or one of its sub-components. The backbone was an AugReg IN1K ViT-B/16._

|                          | Textures | Flowers102 |
| ------------------------ | -------- | ---------- |
| attn.proj                | 59.0     | 60.5       |
| attn.proj + attn.qkv (v) | 60.9     | 59.2       |

_**Table 32. Combining gradients may improve performance:** comparison of the downstream accuracy of `attn.proj` FUNGI features augmented (or not) with gradient features from the `v` of the `qkv` gradients. The backbone was an AugReg IN1K ViT-B/16._

Finally, we do plan to include the discussions that surfaced in the review in the paper, as they will definitely improve the final manuscript. Indeed, we will release all code as open source, including a plug-and-play package to extract FUNGI features from any transformer backbone, e.g. `features = fungi(model, layer='7.attn.v')`.

We're happy to address any other feedback or provide clarifications as needed.
Thank you for the detailed reply. 

**About evaluation on other tasks**: Evaluation on linear probe, clustering and in-context learning are good. It's also great to see that these experiences are carefully conducted in a correct way, e.g., to choose L2-regularization strength for linear probe. From my own experience, the performance of linear probe would be tricky without a proper regularization strength.

**About related work and intuition of FUNGI**: the explanation that FUNGI can be regarded as update-free fine-tuning on other objectives is interesting.

**About comparison to random Gaussian matrix**: Yes I'm mentioning TRAC [5] for the projection with random Gaussian matrix. I agree that random binary matrix is more memory-efficient. 

**About choice of gradient**: it seems that you could choose the gradient from [attn_qkv, attn_proj, mlp.fc1, mlp.fc2] as features. From Figure 8 in the paper, gradient in the early layer seems not helpful. In practice, can you explain which part of gradient to choose in order to get best performance? Will the combination of gradients from different layers/modules be helpful (many people just use full gradient of the model, which is very expensive and might not perform very well)? 

Overall, I'm glad to see the response from the authors. I'd raise my score to 8 and hope athors would include these changes in the modified version (especially the intuition of using gradient feature) and release their code in the future.