Unsupervised Meta-Learning via In-Context Learning

## Abstract

Abstract Unsupervised meta-learning aims to learn feature representations from unsupervised datasets that can transfer to downstream tasks with limited labeled data.
In this paper, we propose a novel approach to unsupervised meta-learning that leverages the generalization abilities of in-context learning observed in transformer architectures. Our method reframes meta-learning as a sequence modeling problem, enabling the transformer encoder to learn task context from support images and utilize it to predict query images.
At the core of our approach lies the creation of diverse tasks generated using a combination of data augmentations and a mixing strategy that challenges the model during training while fostering generalization to unseen tasks at test time.
Experimental results on benchmark datasets showcase the superiority of our approach over existing unsupervised meta-learning baselines, establishing it as the new state-of-the-art in the field. Remarkably, our method achieves competitive results with supervised and self-supervised approaches, underscoring the efficacy of the model in leveraging generalization over memorization.

## 1 Introduction

Meta-learning, or *learning-to-learn*, empowers learning systems with the ability to accumulate knowledge from multiple tasks, enabling rapid adaptation and generalization to new tasks [, ]. Traditional meta-learning approaches typically rely on labeled data to construct tasks during meta-training. However, collecting large labeled datasets in real-world applications is challenging and often impractical. Addressing this issue, unsupervised meta-learning (UML) approaches aim to leverage unlabeled data to learn transferable feature representations, enabling adaptation to new tasks with limited labeled data [].

Various approaches have been proposed to address the UML problem [, , , , , ].
However, UML still faces several challenges. Existing UML methods often rely on simple data augmentations to construct the training tasks, while following the standard meta-learning task sampling pipeline for the evaluation phase. This results in a significant difference between training and testing tasks, constraining the model’s ability to generalize to unseen tasks during inference and requiring additional fine-tuning on the test domain. Furthermore, existing UML approaches typically assume that the training and test datasets belong to the same domain. In our framework, we loosen this assumption resulting in a more challenging setting that necessitates a better model generalization compared to usual meta-learning applications. We refer to this as the *cross-domain* scenario.

In this paper, we propose a novel approach to UML that addresses these challenges by leveraging in-context learning within a transformer architecture [, ]. In-context learning allows the model to use the context provided by a sequence of input-output pairs to make predictions on new input data.
Inspired by recent advancements in large language models (LLMs) [, , ], we formulate meta-learning as a sequence modeling problem, where a task is seen as a sequence of support images and an unknown query image. The support set is treated as the *context* utilized by the model to predict the class of the query image.
We call our approach CAMeLU, which stands for Context-Aware Meta-Learning in Unsupervised scenarios.
Central to our approach is a novel task creation mechanism that enables the generation of a large number of different tasks from an unlabeled dataset. Drawing inspiration from the natural decision process of learning by analogy [], we construct tasks that closely resemble the structure of those encountered during inference.
Specifically, we use a combination of different data augmentation techniques based on basic image manipulations [] for generating the samples in the support set. Conversely, a strategy similar to *mixup* [] is employed to generate query images by combining a support element, after applying a distinct augmentation function, and an image randomly sampled from the training dataset.
This process ensures that the query contains sufficient information from the support image to be classified as the latter, while introducing diversity by blending them. Consequently, query images appear distinct from their corresponding support images while still belonging to the same class, better mimicking the tasks seen at test time and hence enhancing generalization.
Following task creation, support and query images are encoded using a fixed pre-trained feature extractor. The resulting latent representations are aggregated into a sequence and passed as input to a transformer encoder along with their label encodings. The transformer encoder learns to extract contextual information from support images and predict the query image in a single pass, eliminating the need for the fine-tuning step during inference. An overview of our approach is visualized in Figure 1.

Figure: Figure 1: Visualization of CAMeLU (with 3-way 5-shot tasks). The left side illustrates the task creation mechanism, where $N$ samples are drawn from an unlabeled dataset $\mathcal{D}_{train}$. Each sample $x_{n}$ is augmented $K$ times to obtain $x_{n,k}^{(sp)}$. A strategy inspired by *mixup* [] is utilized for generating the query set by using an augmented version of $x_{n}$, i.e., $\tilde{x}_{n,j}$. The same pseudo-label $n\in[1,N]$ is assigned to all data generated from the sample $x_{n}$. On the right side, the so-created task is fed into the transformer encoder for predicting the query input. Inspired by CAML [], the transformer encoder processes demonstrations created by concatenating features from a fixed pre-trained feature extractor and a learned class encoder. The symbol $*$ denotes the unknown query label that the transformer encoder aims to predict.
Refer to caption: x1.png

Throughout extensive experiments we demonstrate the effectiveness of the proposed approach to generalize to new tasks in real-time.
Particularly, CAMeLU outperforms other UML baselines across several datasets, establishing itself as the state-of-the-art in the field. It also achieves comparable results to its supervised counterpart and to SSL approaches. While the latter requires fine-tuning on the test domain, CAMeLU obtains comparable performance with a single forward step, highlighting its applicability to real-time applications. Furthermore, by recasting the meta-learning phase as in-context learning within a transformer architecture, we improve efficiency, ensuring the whole training and inference phase can be executed with a consumer device with 8GB VRAM.

The main contributions of this paper are as follows:

- •
We introduce CAMeLU, a novel UML method that leverages in-context learning within a transformer architecture, reframing meta-learning as a sequence modeling problem.
- •
We propose a novel task creation mechanism that generates diverse few-shot tasks from unlabeled datasets using a combination of data augmentations and a mixing strategy. This ensures better alignment between training and testing tasks, thus improving generalization performance.
- •
We demonstrate that CAMeLU outperforms existing UML baselines across five datasets, without the need for fine-tuning to the test domains.
- •
We investigate the ability of CAMeLU to generalize across various datasets, including those significantly different from the training data.

## 2 Related work

#### Unsupervised meta-learning.

Meta-learning is a well-studied field in the machine learning community due to its ability to enable models to quickly adapt to tasks with limited labeled data. Pioneering work in the field [, , , , ] considers the scenarios where a large labeled dataset is available for meta-training, a challenging requirement in real-world applications. UML addresses this challenge by extracting meaningful information from unsupervised data that can be transferred to downstream tasks with limited labeled data. Different techniques have been explored in the literature to construct diverse tasks. CACTUs [] applies clustering in the embedding space and assigns the same pseudo-label to all images in the same cluster. Other methods focus on generating synthetic samples, either using data augmentations, as in
UMTRA [], or leveraging interpolation in the latent space of a generative model []. Differently, Meta-GMVAE [] and Meta-SVEBM [] use variational autoencoders and memory-based models for pseudo-label generation.
Recent methodologies have also incorporated SSL techniques [] into UML methods. In particular, Set-SimCLR [] builds on top of the SimCLR [] approach and reframes meta-learning as a set-level problem, while PsCo [], inspired by MoCo [], utilizes a momentum encoder and a queue of previous samples to improve pseudo-labeling and construct diverse tasks for UML applications. Similarly, BECLR [] introduces an approach for unsupervised few-shot learning by proposing a constrastive representation learning framework, instead of meta-learning.

#### Data augmentation.

Several UML approaches rely on data augmentation to construct the training tasks [, , ]. However, traditional transformations such as rotation, translation, cropping, resizing, and flipping [] might generate images that are too similar to the original ones, ending up in tasks with low in-class variability between the support and query images. This creates a problem when the model needs to generalize to test tasks, where the query data are different instances than the support ones, not only augmented versions of them. In this paper, we addressed this limitation by generating query images using a strategy inspired by *mixup* [] to enhance model generalization. Similarly to *mixup*, which performs linear interpolation of the feature vectors at the pixel level, other strategies based on mixing images comprise CutMix [], PatchMix [], and Manifold Mixup [].

#### In-context learning.

In-context learning refers to the ability to perform a new task via inference alone by conditioning on a few input-output pairs and making predictions for new inputs []. While typical of LLMs [, , ], this ability has also been explored in different fields, such as in-painting [, ], image segmentation [], and notably meta-learning [, , , ]. In particular, GPICL [] shows that transformers can be meta-trained to act as general-purpose in-context learners. Similarly, CAML [] proposes a universal meta-learner by rephrasing the meta-learning framework as a sequence modeling problem and employing a transformer model for few-shot classification. However, this approach is designed for supervised meta-learning, thus requiring labels both during the training and inference phases. Inspired by these, we propose a new approach that
integrates the in-context learning ability of transformers with a novel task creation mechanism to solve the UML problem.

## 3 Proposed approach

Our proposed approach, *Context-Aware Meta-Learning in Unsupervised scenarios* (CAMeLU), leverages the in-context learning ability of transformers to address the challenges of UML. These challenges include the need to construct meaningful tasks from unlabeled data and the requirement for models to generalize effectively to new tasks during inference. CAMeLU consists of two phases that are intertwined during the model training. Initially, tasks are automatically constructed from an unlabeled dataset utilizing a combination of two strategies. Subsequently, we reformulate the meta-learning framework as a sequence modeling problem, aiming to harness the in-context learning capability of a transformer. This enables the model to extract context from the support samples and predict the unknown query samples without requiring any fine-tuning during the inference phase. We delve into the two phases in Sect. 3.1 and Sect. 3.2, respectively.

### 3.1 Task creation

Central to our proposed approach is the task creation mechanism. In meta-learning, a task $\mathcal{T}_{i}$ corresponds to a data generating distribution $\mathcal{T}_{i}\triangleq\{p_{i}(x),p_{i}(y|x)\}$, and consists of data from $N$ distinct classes. The data sampled from each task is divided into a *support set*, $D_{i}^{(sp)}$, containing $K$ training examples per class, and a *query set*, $D_{i}^{(qr)}$. At meta-test time, only the support set $D_{new}^{(sp)}$ of a task $\mathcal{T}_{new}\sim\mathcal{D}_{test}$ is labeled and used to fine-tune the model and make accurate predictions on the unlabeled query set. Contrary to supervised meta-learning, tasks in UML are only available at test time, while a large unlabeled dataset $\mathcal{D}_{train}$ is available during training. The main goal is to extract prior knowledge from this unlabeled dataset that can be generalized to a target task, $\mathcal{T}_{new}\sim\mathcal{D}_{test}$, during inference. A critical aspect of UML approaches lies in the task creation mechanism to create tasks from $\mathcal{D}_{train}$, which must ensure that the constructed training tasks reflect the structure of those encountered during testing, thereby facilitating effective generalization to novel tasks at test time.
To do so, we employ two distinct strategies for constructing the support and query sets of each task.

For the support set, we randomly sample $N$ images from $\mathcal{D}_{train}$ under the assumption that they belong to distinct categories, as shown in Figure 1. This assumption is reasonable when $N<<C$, where $C$ denotes the total number of classes in $\mathcal{D}_{train}$, which is satisfied using a large training dataset. If we assume that all samples are equally distributed among the classes, i.e., $m$ samples per class, the probability that two or more samples are in the same class is equal to

$$ $\textnormal{P}=1-\frac{(C\cdot m)\cdot((C-1)\cdot m)\cdots((C-N+1)\cdot m)}{(C \cdot m)\cdot(C\cdot m-1)\cdots(C\cdot m-N+1)}=1-\frac{C!\cdot m^{N}\cdot(C \cdot m-N)!}{(C-N)!\cdot(C\cdot m)!}.$ $$

For example, the probability for a 5-way classification on the ImageNet-964 dataset used in our experiment is around $0.01$, which is negligible.
To emulate the $K$-shot scenario typical of meta-learning tasks, we augment each of the $N$ images $K$ times, with an augmentation function $\mathcal{A}_{k}$ sampled from a predefined set of transformations $\mathbfcal{A}$, and we assign the same pseudo-label $n\in[1,N]$ to all data generated from the same sample $x_{n}$. Specifically, for each image $x_{n}$, $K$ augmentation functions are applied to obtain $x_{n,k}^{(sp)}=\mathcal{A}_{k}(x_{n})$ with $\mathcal{A}_{k}\sim\mathbfcal{A}$ and $k=1,\ldots,K$. One requirement of $\mathcal{A}_{k}$ is that the function must preserve class membership, i.e., $x_{n}\in c\rightarrow\mathcal{A}_{k}(x_{n})\in c$, for $c\in C$. Although this property cannot be directly verified due to the lack of class information in the training set, it is reasonable to assume that it holds by selecting transformations that minimally alter the image content.

For the query set, we employ a different approach. We demonstrate in Appendix A.5 that simply applying data augmentations sampled from $\mathbfcal{A}$ is not sufficient for creating a query set resembling those in test tasks. At test time, the query set samples are different instances belonging to the same $N$ classes encountered in the support set, not augmented versions of the support samples. However, since $\mathcal{D}_{train}$ is unlabeled, we need a strategy to create new samples with the same implicit classes as those in the support set.
For each query image $x_{j}^{(qr)}$ that we want to generate, we randomly select an image $x_{n}$ from the ones sampled for the support set generation and we apply an augmentation function $\mathcal{A}_{j}\sim\mathbfcal{A}$, possibly different from the one used for the support generation. We then propose a new strategy inspired by *mixup*, where we combined the augmented image $\tilde{x}_{n,j}=\mathcal{A}_{j}(x_{n})$ and an image $z_{j}$ sampled from $\mathcal{D}_{train}$ according to:

$$ $x_{j}^{(qr)}=\lambda z_{j}+(1-\lambda)\tilde{x}_{n,j}$ (1) $$

where $\lambda\sim Beta(\alpha,\beta)$ with $\alpha=1,\beta=1$ and $\lambda\in(0,0.5)$, and $x_{j}^{(qr)}$ is assigned the same label $n$ as the support samples generated from $x_{n}$.
By merging a small proportion of a new image $z_{j}$ into $\tilde{x}_{n,j}$, we enhance diversity in the query set with respect to the images in the support set. This strategy enforces the model to extract robust features and effectively generalize to scenarios where query images differ from the support samples, as commonly encountered at test time.

This task-creation mechanism can be seen as a task augmentation strategy [, ] that allows the generation of a large number (almost infinite) of diverse tasks. This is particularly useful for meta-learning and in-context learning applications where the model needs to acquire knowledge from a multitude of tasks to generalize to unseen tasks sampled from different domains.

#### Differences with mixup .

While the strategy used for generating the query images draws inspiration from the *mixup* strategy proposed in [], there are some substantial differences. The aim of *mixup* is to develop a new data augmentation strategy to expand the number of training examples and diversify the data distribution used for training, thereby enhancing the robustness and generalization of neural networks. In CAMeLU, the primary objective of merging images is to encourage the model to learn even in scenarios where only a fraction of the class context is present in the image. In CAMeLU, $\lambda$ is sampled from a uniform distribution (obtained with a $Beta$ distribution with $\alpha=1,\beta=1$) in $(0,0.5)$, guaranteeing that the amount of information from $z_{j}$ that is embedded into $x_{j}^{(qr)}$ is less than 50%, thus ensuring that the assigned label is consistent with the class of the support images generated from $x_{n}$. Indeed, we assign the same label $n$ to $x_{j}^{(qr)}$, forcing the network to learn to retrieve information in $x_{j}^{(qr)}$ that is related to the category of $x_{n}$. Contrarily, *mixup* creates new examples by interpolating both images and labels at the scope of limiting memorization over the training distribution.

### 3.2 In-context learning method

Following task creation, we rephrase the meta-learning framework as a sequence modeling problem. Inspired by recent developments in LLMs [, , , , ], we treat each task as a prompt, where the support embedding, together with the learned projected labels, form the demonstration context, whereas the query represents the classification problem that the network is required to solve. A model is said to *in-context learn* a task if it can approximate $y_{j}^{(qr)}$ for a new query input $x_{j}^{(qr)}$ by conditioning on a sequence $S_{i,j}$ containing in-context (support) examples and one query input defined as follows:

$$ $S_{i,j}=\left((x_{1}^{(sp)},y_{1}^{(sp)}),\ldots,(x_{NK}^{(sp)},y_{NK}^{(sp)}) ,x_{j}^{(qr)}\right),\quad j=1,\ldots,Q,$ (2) $$

with $Q$ the number of query samples to classify and $NK$ the total number of context (support) samples.
Formally, $M_{\theta}$ can in-context learn a task $\mathcal{T}_{i}$ if it can predict $y_{j}^{(qr)}$ with an average error

$$ $\mathbb{E}\left[\sum_{j=1}^{Q}\ell(M_{\theta}(S_{i,j}),y_{j}^{(qr)})\right]<\epsilon,$ (3) $$

where $\ell$ is the loss function, $S_{i,j}$ is the sequence associated to $x_{j}^{(qr)}$ in $\mathcal{T}_{i}$, and $y_{j}^{(qr)}\in[1,N]$.

To achieve this, we design a model comprising three components: (1) a feature extractor $f_{\psi}$, (2) a class encoder $g_{\phi}$, and (3) a transformer encoder with a linear projection layer on top, i.e., $M_{\theta}$. The feature extractor aims to map support and query samples into a latent space where images with similar characteristics and semantic meaning are assigned similar representations. In Appendix A.4 we explore various feature extractors for this purpose, including those pre-trained via a supervised approach or leveraging an SSL technique.
The resulting representations are then concatenated with a class embedding. The class embeddings for the support representations are generated by encoding the corresponding classes using the class encoder $g_{\phi}$. However, as the classes of the queries are unknown, a randomly initialized learnable vector is appended to each query representation.
The so-combined embeddings are then organized into sequences $S_{i,j}=\left((f_{\psi}(x_{1}^{(sp)}),g_{\phi}(y_{1}^{(sp)})),\ldots,(f_{\psi}
(x_{NK}^{(sp)}),g_{\phi}(y_{NK}^{(sp)})),f_{\psi}(x_{j}^{(qr)})\right),$ $j=1,\ldots,Q,$ resembling the one in Equation 2. These sequences are fed into the transformer encoder, and only the transformer output corresponding to the query sample is selected and passed through a projection layer to predict the query label. This process iterates for all queries in the task, and the aggregated loss is employed for model training. In particular, the training process can be formulated as an optimization process where the objective is as follows:

$$ $\min_{\theta,\phi}\;\mathbb{E}_{S_{i}}\left[\frac{1}{Q}\sum_{j=1}^{Q}\ell(M_{ \theta}(S_{i,j}),y_{j}^{(qr)})\right]$ (4) $$

with $S_{i}=\{S_{i,j}\}_{j=1}^{Q}$ denoting the set of sequences associated to each task $\mathcal{T}_{i}$ generated from $\mathcal{D}_{train}$ and $\ell$ is the cross-entropy loss function.

During evaluation, when a new task is presented, the available examples in $D_{new}^{(sp)}$ are utilized as contextual information to guide the classfication of the query samples, without requiring any fine-tuning or adaptation steps.

## 4 Experiments

In this section, we demonstrate the effectiveness of CAMeLU across different datasets, and we compare the results with several baseline methods. In particular, we provide a quantitative comparison with UML baselines in Sect. 4.3, and we highlight the ability of CAMeLU to leverage generalization over memorization in Sect. 4.4. We then present the results with a small-scale training dataset in Sect. 4.5 and a comparison with SSL methods in Sect. 4.6.

### 4.1 Datasets and baselines

For the evaluation, we use two generic object recognition datasets, i.e., *mini*ImageNet [] and CIFAR-fs [], and three fine-grained image classification datasets, i.e., CUB [], Aircraft [], and Meta-iNat []. While *mini*ImageNet and CIFAR-fs share some similarities with ImageNet-1k, as some classes appears in all three datasets, CUB, Aircraft, and Meta-iNat focus on more specialized domains, ensuring a rigourous cross-domain evaluation. Each dataset is split into training, validation, and test sets following the splits in [] and [] for *mini*ImageNet and CIFAR-fs, respectively, and in [] and [] for the remaining datasets. All labels are removed from the datasets during the training phase.

We compare the results of CAMeLU with standard UML approaches such as CACTUs [], UMTRA [], Meta-GMVAE [], and PsCo []. These methods are evaluated in-domain as recommended in the original papers, with training and testing performed on the same dataset. While this setup is relatively simpler than the cross-domain evaluation employed for CAMeLU, applying these methods in a cross-domain scenario may not be fair, as they were not explicitly designed for such a challenging scenario.
Only PsCo [] is further evaluated in a cross-domain setting, as the authors demonstrate its adaptability to this scenario through an additional adaptation phase to the test domain.
We also compare CAMeLU with BECLR [] in Section 4.5, a contrastive framework for unsupervised few-shot learning. Although BECLR does not utilize meta-learning, it serves as a strong baseline for unsupervised few-shot learning. Additionally, CAMeLU is compared to CAML [], a supervised meta-learning approach that assumes tasks are available both during the training and testing phases and leverages the in-context ability of transformer architectures to generalize to new tasks. Due to their similarities, we refer to CAML as the supervised counterpart of CAMeLU. Furthermore, Section 4.6 provides a comparative analysis with two fine-tuned state-of-the-art self-supervised trained networks, namely SimCLR [] and SwAV [].

### 4.2 Training details

We report the results following the $N$-way $K$-shot classification task typical of meta-learning algorithms, where $N=5$ and $K=1$ or $K=5$. All models are trained for $100$ epochs, $500$ episodes per epoch, and $100$ fine-tuning steps at test time if required by the method. For CAMeLU, we choose not to apply any fine-tuning strategy to prove the strength of the training stage that does not require additional parameter updates during the inference phase.
Furthermore, we introduce ImageNet-964, a variant of the original ImageNet-1k dataset [] where the classes belonging to the validation and test splits of *mini*ImageNet are removed to prevent data leakage when evaluating the model on *mini*ImageNet - a problem that is not taken into consideration by previous studies [, ]. To provide a fair comparison, all cross-domain methods are trained using ImageNet-964.
For CAMeLU, we use a feature extractor pre-trained using ResNet-50 [] on ImageNet-964 and a class encoder consisting of a single learnable layer. In Appendix A.4, we also report the results with different feature extractors. The transformer encoder consists of 8 encoder layers, each incorporating a multi-head self-attention block with 8 attention heads, an MLP with a reverse bottleneck of $3072$ and an input-output feature size of $2304$, where the last $2048$ features is the ResNet-50 feature vector appended to the $256$ encoding of the labels. Finally, a single projection layer maps the transformer output to the predicted category. The model is trained with the Adam optimizer with a learning rate of $10^{-5}$ and a warmup cosine scheduler as proposed in the original paper []. To account for statistical variations, each algorithm is run three times in full and the complete results reporting the standard deviations are presented in Appendix A.10. The experiments are executed using Python and the PyTorch library on an Nvidia GeForce RTX 3070 Ti Laptop GPU with 8GB of VRAM. Further ablation experiments and competitors required a more capable architecture and are executed on an Nvidia A100-SXM4 GPU with 40GB of VRAM. More details about the training settings can be found in Appendix A.1, while the code will be released upon acceptance of the paper.

### 4.3 Comparative results

Table: Table 1: Performance comparison on *mini*ImageNet, CIFAR-fs, CUB, Aircraft, and Meta-iNat datasets for 5-way 1-shot and 5-way 5-shot scenarios. Cross-domain approaches are trained using ImageNet-964 and a ResNet-50 feature extractor. The symbol $\dagger$ indicates results that are affected by data leakage. The bold font highlights the best performing UML approach for each setting. Results show the average across three complete runs of the algorithms. Complete results with standard deviations are reported in Table 10 in Appendix A.10.

Table 1 provides an overview of the experimental results for both the 5-way 1-shot and the 5-way 5-shot scenarios.
The results demonstrate that CAMeLU outperforms the existing UML methods, regardless of the difference in the evaluation setting. As highlighted in Section 4.1, CACTUs, UMTRA, and Meta-GMVAE are evaluated only in-domain, requiring knowledge about the test domain prior to training. This is not necessary for CAMeLU as it demonstrates high performance in the challenging cross-domain scenario.
Even compared to PsCo, the only UML method designed for cross-domain applications, CAMeLU exhibits a performance improvement in all datasets. Furthermore, PsCo requires a fine-tuning phase to adapt to the test domain, whereas CAMeLU achieves good performance with a single forward pass, enhancing its applicability to real-time applications.
It is also worth noting that CAMeLU achieves comparable performance to its supervised counterpart, CAML, when evaluated on *mini*ImageNet and it even outperforms CAML when evaluated on more dissimilar domains, such as CUB, Aircraft, and Meta-iNat. This finding highlights the efficacy of the task construction strategy used in CAMeLU, which acts as a sort of task augmentation and enhances the generalization capability of the model.

### 4.4 Memorization to generalization phase shift

During the training of CAMeLU, we observed a distinct trend in the validation accuracy, similar to the findings in []. Figure 2 illustrates this pattern, showing the validation accuracy relative to its initial value, or, in other words, how much the model learns from datasets different from the one we are training on. Specifically, the curves in Figure 2 resemble a logistic curve,

Figure: Figure 2: Analysis of learning behavior when transferring knowledge from different prior datasets. The relative validation accuracy shows the difference between the current and first epoch accuracy on the validation set of *mini*ImageNet, CIFAR-fs, CUB, and Aircraft. CAMeLU is trained with ImageNet-964.
Refer to caption: x2.png

which can be divided into three phases that we denote as *memorization*, *learning*, and *generalization*. In the memorization phase, the model memorizes the tasks seen during training and extends this knowledge to unseen tasks, resulting in a slight improvement for datasets with high similarity with ImageNet-964 (e.g., *mini*ImageNet and CIFAR-fs). For the other datasets, instead, transferring this knowledge can even result in a performance decrease due to the intrinsic domain distance of the dataset (see CUB and Aircraft, which are fine-grained datasets).
As training progresses and the model observes more tasks, the learning phase occurs. This phase is characterized by a transition to the learning-to-learn state where the model learns to identify the tasks and to extract the features that are more useful for solving them. The duration of this phase varies, with datasets like *mini*ImageNet and CIFAR-fs exhibiting rapid learning within approximately $10$ epochs, while datasets such as CUB and Aircraft may necessitate up to 40 epochs. This timespan depends on several factors, including the similarity between the training and evaluation datasets, the size of the test dataset, and the model’s learning ability [, ]. For instance, CUB, with its fine-grained nature and small test set size (around $1770$ images), necessitates a longer learning phase compared to the *mini*ImageNet dataset (which has a test set with $12\,000$ images).
Subsequently, in the generalization phase, the model can generalize to tasks significantly different from those observed during training using a single forward pass. Further analyses about the generalization capabilities of CAMeLU and the number of epochs required for reaching the generalization phase are presented in Section 4.5 and Appendix A.8.

### 4.5 Generalization on small-scale datasets

Table: Table 2: Accuracy results obtained training PsCo, BECLR, and CAMeLU with a small-scale dataset, namely *mini*ImageNet, denoted as (*mini*) in the table. Results show both in-domain performance (on the test set of *mini*ImageNet) and cross-domain performance on CIFAR-fs, CUB, Aircraft, and Meta-iNat. The average results across three complete runs of the algorithms are reported. Complete results with standard deviations are presented in Table 11 in Appendix A.10.

While most studies on training transformer architectures focus on large-scale training datasets, we investigate the generalization capabilities of CAMeLU using a small-scale training dataset. Specifically, we train CAMeLU on *mini*ImageNet and evaluate its performance both in-domain (i.e., on the test set of *mini*ImageNet) and cross-domain on CIFAR-fs, CUB, Aircraft, and Meta-iNat.
CAMeLU demonstrates effective generalization in this scenario, showing impressive performance in both in-domain and cross-domain settings, as shown in Table 2, surpassing PsCo and BECLR by a large margin.

Additionally, a comparison of CAMeLU’s performance when trained on a small-scale dataset like *mini*ImageNet (Table 2), on ImageNet-964 (Table 1), and on a large-scale dataset (Table 5 in Appendix A.3) show that our method is only slightly affected by the size of the training dataset.

Figure: Figure 3: Relative validation accuracy comparison between CAMeLU (orange) and CAML (blue) when evaluated in-domain on *mini*Imagenet. The relative validation accuracy is computed as described in Section 4.4. The curve obtained with CAMeLU reflects the three phases of *memorization*, *learning*, and *generalization* even when using a small-scale dataset.
Refer to caption: x3.png

This robustness enhances CAMeLU’s applicability to scenarios where only a small unlabeled training dataset is available, which is common in real-world applications.

Finally, Figure 3 shows the relative validation accuracy of CAMeLU and CAML while trained and evaluated on *mini*ImageNet. While the curve obtained with CAMeLU reflects the three phases of *memorization*, *learning*, and *generalization* discussed in Section 4.4, the relative validation accuracy of CAML remains flat. This difference may be attributed to the task creation mechanism of CAMeLU, which acts as a task augmentation strategy, increasing the variability of tasks presented to the model during training and thereby enhancing its generalization capabilities.

### 4.6 Comparison with SSL methods

Table: Table 3: Comparison between CAMeLU and SSL approaches for the 5-way 1-shot and 5-way 5-shot scenario on *mini*ImageNet, CIFAR-fs, CUB, Aircraft, and Meta-iNat. The symbol $\dagger$ indicates results that are affected by data leakage. Results show the average across three complete runs of the algorithms. Complete results with standard deviations are reported in Table 12 in Appendix A.10.

In this section, we compare CAMeLU with SimCLR [] and SwAV []. For training SSL methods in our experiments, we employed a backbone network with a ResNet-50 architecture pre-trained on ImageNet-1k obtained from PyTorch Lightning Bolts []. While this setup leads to data leakage when evaluated on *mini*ImageNet, due to overlap between the test and training classes, pre-training these SSL approaches from scratch using a different training dataset was beyond our available computational resources. To facilitate model adaptation to the test domain, we fine-tuned a classification layer on top of the pre-trained backbone using SGD with initial learning rate of $0.01$, momentum of $0.9$, weight decay of $10^{-4}$, and $100$ fine-tuning steps per task, following []. This setup differs from the evaluation setting used in CAMeLU, where predictions are obtained with a single forward pass, leveraging the in-context learning ability of transformer architectures. However, SSL approaches must adapt to the test domain before label predictions, resulting in a less challenging evaluation setting than CAMeLU.
Results for SSL approaches are averaged over $500$ test tasks and presented in Table 3.
While SSL approaches outperform CAMeLU on *mini*ImageNet and CIFAR-fs, their performance decreases when evaluated on the other datasets. CUB, Aircraft, and Meta-iNat are fine-grained datasets significantly different from ImageNet-1k, challenging the transferability of features learned by SSL methods to these datasets. Moreover, the high performance on *mini*ImageNet and CIFAR-fs may be attributed to the presence of data leakage with ImageNet-1k and the high similarity with CIFAR-fs, as discussed in Section 4.2. CAMeLU, in contrast, demonstrates effective generalization to tasks sampled from these datasets, once again highlighting its generalization ability over mere memorization.

## 5 Conclusion

In this paper, we introduce CAMeLU, a novel approach for UML that leverages the in-context learning capabilities of transformer architectures to extract context from the support samples and make effective predictions on the query data. CAMeLU reframes meta-learning as a sequence modeling problem, where support images provide task context for predicting query images. At the core of CAMeLU is a novel task creation mechanism that generates diverse tasks from an unlabeled dataset, promoting effective generalization to unseen tasks.
Our experimental results showcase the superiority of CAMeLU over existing UML methods, highlighting the applicability of the proposed method to domains different from the training one. Notably, CAMeLU can generalize to new domains with a single forward pass (real-time predictions), and it even outperforms its supervised counterpart thanks to its task creation mechanism. Furthermore, the proposed model can be stored and trained with a single GPU with only 8GB of VRAM, underscoring its efficiency in learning-to-learn in-context, rather than using a meta-training phase typical of previous meta-learning approaches.

Future research directions may explore extensions of CAMeLU to more complex domains, as well as investigations into further improving the task creation mechanism for enhanced generalization. It would be interesting to incorporate SSL techniques to obtain more robust feature representations and enhance generalization capabilities. Additionally, conducting further investigation into CAMeLU’s ability to encourage generalization over memorization would provide valuable insights into its learning dynamics and potential areas for improvement.

## Appendix A Appendix

### A.1 Experimental details

#### Datasets.

For training CAMeLU, we use ImageNet-964, which is a variant of the original ImageNet-1k dataset [] where classes belonging to the validation and test splits of *mini*ImageNet [] are removed. This results in a total of $1\,234\,487$ images for training the model compared to the $1\,281\,167$ in the original ImageNet-1k dataset. When a multi-dataset approach is utilized for training CAMeLU (see Appendix A.3), MSCOCO [] and Fungi [] are loaded into the program and used together with ImageNet-964 for creating the whole training dataset. MSCOCO is a dataset originally proposed for object detection, where each image is assigned to $G$ classes corresponding to the $G$ objects present in it. To use it for image classification, we replicate each image $G$ times and we assign to each of them one of the $G$ classes. In this way, we obtain a dataset with $117\,266$ images for training, and we rely on the fact that the transformer is capable of applying self-attention to the object of the class in question. Fungi is a fine-grained dataset with a size of only $64\,307$, which is two orders of magnitude smaller than the ImageNet-964 and MSCOCO.
For evaluation and for in-domain training of the baselines, we use *mini*ImageNet, CIFAR-fs, CUB, Aircraft, and Meta-iNat. *mini*ImageNet is split into train/validation/test using the splits proposed in [], resulting in $38\,400$ images for training, $9600$ for validation, and $12\,000$ for testing. The same number of images are also present in CIFAR-fs, and the splits follow the work in []. CUB and Aircraft, instead, are two fine-grained datasets with a smaller size compared to the others. CUB [] consists of $8239$ in the training set, $1779$ in the validation set, and $1770$ in the test set, while Aircraft has respectively $7000$/$1500$/$1500$ images in the train/validation/test sets []. Finally, Meta-iNat [] consists of $243\,986$ images split into $1135$ classes, with $227$ reserved for testing. All images are resized to $224\times 224$ and normalized with zero mean and unit variance before input into the model. For the UML baselines, due to the smaller model size utilized in the esperiments, images are resized to $84\times 84$, as suggested in the original papers [, , , ].

#### CAMeLU.

The architecture used for CAMeLU consists of a fixed pre-trained feature extractor, a class encoder, and a transformer encoder. The feature extractor is pre-trained using ResNet-50 on ImageNet-964 following the same architecture and hyperparameters in [].
The class encoder is a single learnable layer with a dimensionality of $256$ and initialized with Kaiming initialization [].
Image embeddings are concatenated with class embeddings before being fed into the transformer encoder. This results in a vector with a total length of $2304$, composed of $2048$ features from the image embeddings and $256$ from the label embeddings. When ablating the feature extractor with CLIP [] in Appendix A.4, a ViT-B/16 encoder architecture is utilized and downloaded from the Hugging Face website []. The pre-training is performed using a large dataset with $400$ million (image, text) pairs [], and it is fixed during the training phase of CAMeLU. The image embedding’s output size decreases to $1024$, resulting in an input vector length of $768$ and a reduced memory complexity compared to ResNet-50. The transformer encoder comprises 8 encoder layers. Each layer consists of 8 attention heads and an MLP with a reversed bottleneck of $3072$ (with GeLU activation function). A projection layer completes the model architecture to map the transformer output to a class prediction. This architecture enables us to store the entire model in an Nvidia GeForce RTX 3070 Ti Laptop GPU with 8GB of VRAM, while a further reduction of memory can be achieved by utilizing CLIP on ViT-B/16 as feature extractor, which requires only 4 GB of VRAM to store the entire model.

For the task creation mechanism, 3 augmentation functions are selected from a list comprising cropping, rotation, horizontal flip, grayscale, color jittering, gaussian blur, and random affine transformation. The exact parameters used in our experiments for each augmentation function are detailed in Table 4. For the query set, an additional pixel-level mixing strategy with $\lambda\sim Beta(\alpha,\beta)$ with $\alpha=1,\beta=1$ and $\lambda\in(0,0.5)$ is utilized. More details about this selection choice can be found in Appendix A.6.

The training of CAMeLU is performed for $100$ epochs, with $500$ episodes each, using the Adam optimizer with an initial learning rate of $10^{-5}$ and a warmup cosine scheduler with $1500$ warmup steps and a final learning rate of $10^{-6}$. For the evaluation, instead, a single forward pass is performed and the accuracy between the output and the true label is calculated on the query set of each given task. Results are then averaged across $500$ tasks, and the mean and standard deviation across three complete runs (consisting of training and evaluation) of the algorithm are used in our experiments.

**Table 4: Complete list of transformations used for generating the support set of each task in CAMeLU. The names of the augmentations are taken from the *torchvision* library in Python.**
| Augmentation | Parameters |
| --- | --- |
| *RandomResizedCrop* | image size $=224$, scale $=(0.2,0.8)$, ratio$=(0.75,1.33)$ |
| *RandomRotation* | degrees $=60$, probability $=1.0$ |
| *RandomHorizontalFlip* | probability $=1.0$ |
| *Grayscale* | output channels $=3$ |
| *ColorJitter* | brightness $=0.2$, contrast $=0.2$, saturation $=0.2$, hue $=0.2$ |
| *GaussianBlur* | kernel size $=3$, sigma $=(0.1,2.0)$ |
| *RandomAffine* | degrees $=0$, shear $=[-45,45,-45,45]$ |

#### Baselines.

We compare our results with UML methods, an unsupervised few-shot learning method, a supervised meta-learning method, and two SSL methods. For the UML baselines, we consider CACTUs-MAML [], CACTUs-ProtoNet [], UMTRA [], Meta-GMVAE [], and PsCo []. All these methods are evaluated in-domain, i.e., using the same dataset for training and evaluation, to adhere to the setting proposed in the original papers. Only PsCo is also extended to the cross-domain scenario that we discuss in this paper.
All methods are trained for $100$ epochs, using the parameters reported in the original papers [, , , ], and evaluated with $100$ adaptation steps on each task when required by the model.
When evaluated in-domain, all approaches use a Conv5 architecture consisting of $5$ convolutional layers with $64$ filters and a kernel size of $3$, followed by batch normalization, ReLU non-linearity, max pooling, and a classifier head. The only exception is Meta-GMVAE. For this method, the authors trained a Conv5 feature extractor with SimCLR and input the learned features into a variational autoencoder (VAE) []. Due to time limitations and the computational resources required to train a model with SimCLR, in our experiments, we used a feature extractor consisting of a pre-trained version of SimCLR on ResNet-50 [] using ImageNet-1k, followed by a projection layer fine-tuned for $100$ steps to the training dataset, as done for the SSL baselines. This approach results in a better performance than the one reported in the original paper [] (see Table 1), likely due to the improved ability of the feature extractor to extract meaningful features. For PsCo, when evaluated on a cross-domain setting, we utilized the ResNet-50 architecture trained on ImageNet-964 to avoid data leakage, and we then applied the model to the test domain using $100$ adaptation steps to it. We also included BECLR [] in our comparison utilizing the same hyperparameters and model architectures proposed in the original paper, given the importance of hyperparameter choice for final performance. Specifically, the ResNet-50 feature extractor was trained only on *mini*ImageNet and evaluated on cross-domain scenarios in Table 2.

To compare our results with CAML [], the same architecture and hyperparameter of our approach are applied to this method. This results in a lower performance for CAML compared to the original paper [], as the reduced size of the model and the different feature extractor (ResNet-50 instead of ViT-CLIP), but it guarantees fair comparisons and lets us train the model with the available computational resources.

We also provide a comparison with two SSL approaches - SimCLR [] and SwAV []. The details for training and evaluation are provided in Section 4.6.

### A.2 In-context learning analysis

Figure: (a) Feature extractor (*mini*ImageNet)
Refer to caption: extracted/5890138/images/tsne_fe_mini.png

To verify the contribution of the in-context learner in CAMeLU, we examine the embedding space learned during inference, both after the feature extractor and the transformer encoder. Figure 4 presents a t-SNE visualization of a single test task, where clusters represent the embeddings of the support classes. For simplicity, we illustrate a 5-way 5-shot task with one query sample for each dataset and we report the Euclidean distance between the query and the centroid of each class. As the dataset complexity increases, we observe greater variation between the embeddings learned from the fixed feature extractor and those refined by the transformer encoder. For instance, with the *mini*ImageNet dataset, the feature extractor alone is able to recognize the class of the query, clustering the query sample with the support samples belonging to the same class. However, in more challenging datasets such as CUB and Aircraft, the embedding space after the feature extractor appears more sparse, reflected by the large Euclidean distance between the query sample and the centroid of each class. In contrast, the transformer encoder significantly improves the representation, producing more compact and well-separated clusters, underscoring its crucial role in CAMeLU. For instance, in the Aircraft dataset, the query would be misclassified as class 5 (in grey) based on the feature extractor alone, but it is correctly classified after passing through the transformer. This highlights the role of the transformer encoder in updating the support and query representations based on the context of the task, not only the image context, improving classification accuracy.

### A.3 Multi-dataset training

Table: Table 5: Comparison of CAMeLU and CAML when trained on the single ImageNet-964 dataset (IN-964) and on a multi-dataset consisting of ImageNet-964 + MSCOCO + Fungi (mds). Results show the mean and standard deviations for the 5-way 1-shot and the 5-way 5-shot settings across three complete runs of the algorithms.

We conduct additional experiments to evaluate the performance of CAMeLU when trained on a large-scale dataset. As our focus is on cross-domain classification through in-context learning, we hypothesize that training on a dataset spanning various concepts could enhance classification performance, as suggested in [, ].
To test this hypothesis, we combine three training datasets with varying levels of granularity: ImageNet-964 [], MSCOCO [], and Fungi []. During each training episode, a dataset is uniformly sampled, and $N$ data points are extracted. These samples are then utilized in our method as described in Section 3.
Table 5 presents the results for CAMeLU and the supervised CAML method. Notably, training with a combination of multiple datasets (denoted as mds in Table 5) yields improved performance for CAML (supervised) compared to training solely on ImageNet-964, likely due to the increased variability in the sampled tasks. However, CAMeLU does not exhibit a similar performance boost, as its task creation mechanism already introduces substantial variability, reducing the benefit of additional dataset diversity. Moreover, the large size of ImageNet-964 (around $80\%$ of the overall dataset), leads to its more frequent selection compared to the other datasets and limits the potential for performance gains from the other datasets. Consequently, to optimize computational resources and time, we conducted all the other experiments by training solely on ImageNet-964.

### A.4 Ablation studies - Feature extractor

Table: Table 6: Ablation study of feature extractors utilized in CAMeLU. The feature extractors include ResNet-50 pre-trained on ImageNet-964 (ResNet50 (IN-964)), ResNet-50 pre-trained on ImageNet-1k (ResNet50 (IN-1k)), ResNet-50 pre-trained on ImageNet-1k with SimCLR and SwAV, as well as a ViT-B/16 architecture pre-trained with CLIP. All models are trained using CAMeLU on (a) ImageNet-964 or (b) using a combination of ImageNet-964 + MSCOCO + Fungi (multi-dataset). The symbol $\dagger$ indicates results that are affected by data leakage. Results show the mean and standard deviations across three complete runs of the algorithms.

To assess the impact of the pre-trained feature extractor, we evaluate CAMeLU with various extractors pre-trained using different strategies. In particular, we compare the effectiveness of a ResNet-50 encoder pre-trained in a supervised manner both on ImageNet-1k and on ImageNet-964, a ResNet-50 pre-trained on ImageNet-1k using two SSL strategies, i.e., SimCLR [] and SwAV [], and a ViT-B/16 architecture pre-trained with CLIP [] on a large dataset with $400$ million (image, text) pairs. The extractors were downloaded from the Hugging Face [] and PyTorch Lightning Bolts [] websites, except for the ResNet-50 architecture pre-trained on ImageNet-964.
Results in Table 6(a) demonstrate that the models pre-trained on ImageNet-1k exhibit significantly higher performance on *mini*ImageNet, compared to other datasets, primarily due to the data leakage issue described in Section 4.2. This issue was mitigated by pre-training the ResNet-50 architecture on ImageNet-964, which results in a drop in the performance on *mini*ImageNet and CIFAR-fs due to the removal of data leakage, making it comparable with the results on CLIP-ViT-B/16. Notably, CLIP-ViT-B/16 stands out as the best performing method, due to its dataset-agnostic nature and its ability to learn representations that generalize across a broad range of tasks.
Furthermore, when training CAMeLU with a multi-dataset approach (Table 6(b)), as described in Appendix A.3, results for CLIP-ViT-B/16 improve further, highlighting its applicability also to datasets significantly different from those used for training []. These findings demonstrate that CAMeLU’s performance scales with the strength of the feature extractor, indicating potential for further investigation as more robust feature extractors become available.
However, in this work, we decided to use the ResNet-50 architecture to obtain fair comparison with previous baselines.

### A.5 Evaluation of the task creation mechanism

Figure: Figure 5: Validation accuracy on *mini*ImageNet (*mini*) and CUB while training CAMeLU with two different task creation mechanisms. Red and purple curves are obtained with our proposed strategy in Section 3.1, while orange and pink curves are obtained by applying only data augmentations based on image manipulations to generate the support and query samples. The training is performed using ImageNet-964.
Refer to caption: x4.png

To assess the effectiveness of the task creation strategy employed in our proposed approach, we conduct a comparative analysis of CAMeLU’s performance under two different task creation mechanisms. Specifically, we evaluate CAMeLU when tasks are generated solely using data augmentations for both the support and query sets, following a strategy similar to UMTRA [], versus employing our proposed approach outlined in Section 3.1. The results presented in Table 7(a) across all the datasets suggest that our proposed strategy enhances the generalization on cross-domain datasets such as CUB, Aircraft, and Meta-iNat. This conclusion is further supported by Figure 5, which show the validation accuracy on *mini*ImageNet and CUB using the two mechanisms discussed before, along with the CLIP-ViT feature extractor described in Appendix A.4. These results confirm that our task creation strategy is more robust, particularly in cross-domain evaluations, even when stronger feature extractors are utilized.

Additionally, we experimented with k-means clustering as an alternative to the proposed task creation strategy. Inspired by CACTUs [], we applied clustering on the embeddings generated by the feature extractor to generate pseudo-labels. The results are presented in Table 7(b) when training on *mini*ImageNet due to the high computational cost of k-means and indicate that our proposed mechanism generalizes better across domains. Furthermore, k-means clustering requires an insight on the number of classes in the training dataset, as choosing a high number of clusters would lead to a lack of samples per class, whereas a low number may hinder generalization. In contrast, CAMeLU does not rely on such assumptions, enhancing its robustness compared to clustering-based approaches.

Table: Table 7: Ablation experiments of the proposed task creation mechanism by (a) generating tasks only using data augmentations for the support and query set on ImageNet-964 and (b) applying k-means clustering on the ResNet-50 embeddings on *mini*ImageNet. Results show the mean and standard deviations across three complete runs of the algorithms in the 5-way 1-shot and 5-way 5-shot scenarios.

### A.6 Query samples generation strategy

We also conducted additional experiments to validate the choice of utilizing Equation 1 for generating query samples. In particular, we compare the results obtained as a linear combination of the augmented image $\tilde{x}_{n,j}$ with the randomly sampled image $z_{j}$ (pixel level), as in Equation 1, and at the patch level, as in []. Specifically, for the latter, we randomly select a patch from $z_{j}$ with an area ratio proportional to $\lambda$, and we paste it into $\tilde{x}_{n,j}$. Figure 6 illustrates an example of these two techniques by mixing two images sampled from ImageNet-964. As shown in Figure 6(c), merging the images at the pixel level results in a mixed image where some information from $\tilde{x}_{n,j}$ and $z_{j}$ is retained in every part of the image. Contrarily, in Figure 6(d), there is no information about $\tilde{x}_{n,j}$ in the lower left corner, forcing the network to attend only to the upper right part of the image to classify it with the same class as $\tilde{x}_{n,j}$. Therefore, we hypothesize that the pixel level strategy is more suitable for our approach as the goal is to attend to the whole image to extract robust features that allow the model to classify the query image with the same class as the support one while ensuring diversity between the two. To validate this, we utilized the Structural Similarity Index ($SSIM$) []. $SSIM$ is used as a metric to measure the similarity between two given images based on three image features: luminance, contrast, and structure. Formally, considering $x$ and $y$ two given images, $SSIM$ is calculated as follows:

$$ $SSIM(x,y)=\left[\frac{2\mu_{x}\mu_{y}+c_{1}}{\mu_{x}^{2}+\mu_{y}^{2}+c_{1}} \right]^{\alpha}+\left[\frac{2\sigma_{x}\sigma_{y}+c_{2}}{\sigma_{x}^{2}+ \sigma_{y}^{2}+c_{2}}\right]^{\beta}+\left[\frac{\sigma_{xy}+c_{3}}{\sigma_{x} \sigma_{y}+c_{3}}\right]^{\gamma}$ (5) $$

where $\mu$ represents the mean of an image, $\sigma$ denotes the standard deviation, $c_{1},c_{2},c_{3}$ are constant values, and $\alpha,\beta,\gamma$ denote the relative importance of each metrics. By assuming $\alpha=\beta=\gamma=1$ and $c_{2}=c_{2}/2$, we get

$$ $SSIM(x,y)=\frac{(2\mu_{x}\mu_{y}+c_{1})(2\sigma_{xy}+c_{2})}{(\mu_{x}^{2}+\mu_ {y}^{2}+c_{1})(\sigma_{x}^{2}+\sigma_{y}^{2}+c_{2})}.$ (6) $$

Instead of applying the above formula all over the image at once, [] proposed a local variant that consists of computing the $SSIM$ index locally and averaging these values to obtain the global $SSIM$ value.
For our purpose, we computed this metric between each of the two images used for the generation, i.e., $\tilde{x}_{n,j}$ and $z_{j}$, and the resulting mixed image, i.e., $x_{j}^{(qr)}$. We then average the results, obtaining an indicator, denoted as $mSSIM$, of how similar the query image is with the images used for the generation, or in other words, how much local information is retained from $\tilde{x}_{n,j}$ and $z_{j}$ into $x_{j}^{(qr)}$. Results are shown in Table 8 for $\lambda=0.25$ and $\lambda=0.49$, confirming the hypothesis that, even for high $\lambda$ values, mixing at the pixel level guarantees more information retained across the whole image compared to using a patch level strategy. This is also confirmed by the results in Table 9, which shows a decrease in the performance when CAMeLU is trained with the patch level strategy for query generation.

Figure: (a) Image $\tilde{x}_{n,j}$
Refer to caption: extracted/5890138/images/xs_resize.png

We also ablate the values of the $\alpha$ and $\beta$ parameters used in the $Beta$ distribution from which $\lambda$ is sampled.
Table 9 presents the results for different values of $\alpha$ and $\beta$ when $\lambda\sim Beta(\alpha,\beta)$ and $\lambda\in(0,0.5)$. The results indicate that the optimal choice for CAMeLU is to select $\alpha=1,\beta=1$, which appears to be a uniform distribution. Additionally, $\alpha=2,\beta=5$ also yields comparable results, highlighting the importance of selecting a sufficiently small $\lambda$ to ensure the incorporation of sufficient information from $\tilde{x}_{n,j}$ into $x_{j}^{(qr)}$ facilitating the model’s ability to classify the latter with the same class as $x_{n,i}^{(sp)}$.

**Table 9: Accuracy results of CAMeLU when trained with different strategies for generating the query samples. *Pixel level mix* refers to the scenario where query samples are generated with Equation 1, while *patch level mix* refers to a strategy similar to the one proposed in []. Results are reported in the 5-way 5-shot scenario with $\lambda\sim Beta(\alpha,\beta)$ and different $\alpha$ and $\beta$ values. Results show the mean and standard deviations across three complete runs of the algorithms.**
|  | miniImageNet | CIFAR-fs | CUB | Aircraft |
| --- | --- | --- | --- | --- |
| Pixel level mix |  |  |  |  |
| $\alpha=0.1,\beta=0.1$ | $90.68\pm 0.67$ | $75.88\pm 2.08$ | $76.31\pm 2.44$ | $35.31\pm 2.57$ |
| $\alpha=0.5,\beta=0.5$ | $91.34\pm 0.24$ | $77.70\pm 0.73$ | $79.52\pm 0.73$ | $37.56\pm 1.92$ |
| $\alpha=1,\beta=1$ | $\mathbf{92.14\pm 0.30}$ | $\mathbf{80.43\pm 0.21}$ | $\mathbf{80.35\pm 0.63}$ | $\mathbf{39.11\pm 1.97}$ |
| $\alpha=2,\beta=5$ | $90.68\pm 1.02$ | $77.00\pm 1.40$ | $79.62\pm 2.50$ | $38.02\pm 1.85$ |
| $\alpha=5,\beta=5$ | $90.63\pm 0.30$ | $78.12\pm 0.15$ | $79.71\pm 0.42$ | $37.57\pm 0.11$ |
| Patch level mix |  |  |  |  |
| $\alpha=1,\beta=1$ | $91.25\pm 0.50$ | $77.80\pm 0.45$ | $76.12\pm 1.06$ | $33.60\pm 1.27$ |

### A.7 Analysis of computational complexity

The core of CAMeLU relies on a transformer architecture, which is known for its computational demands due to the self-attention mechanism.
The transformer model has a computational complexity of $O(n^{2}\cdot d)$ per layer [], where $n$ is the sequence length and $d$ is the hidden dimension. In our context, $n$ includes both the support samples and the query sample. Consequently, the total computational complexity for evaluating $Q$ queries is $O(Q\cdot(NK+1)^{2}\cdot d)$, where $N$ is the number of classes, $K$ the number of shots, $NK+1$ indicates one query per input sequence, and $Q$ is the total number of queries. This results in a quadratic complexity in the number of support samples which can be computationally demanding. However, we have demonstrated in Table 1 that CAMeLU achieves good performance even with only $K=1$ support sample per class. Additionally, further experiments with only one query sample per episode and one support sample per class (i.e., $N=5$, $K=1$, $Q=1$) yield results of $80.74\pm 0.65$ for *mini*ImageNet, $63.07\pm 1.14$ for CIFAR-fs, $54.84\pm 1.41$ for CUB, $30.32\pm 0.76$ for Aircraft, and $55.76\pm 0.08$ for Meta-iNat. These results are comparable to those reported in Table 1 for the 5-ways 1-shot scenario using 25 queries, highlighting that a single query is sufficient for good performance, as also demonstrated in CAML.

### A.8 Quantitative analysis of learning phases

To quantitatively assess the number of epochs required to enter the generalization phase, we propose to approximate the validation accuracy curves with the generalized logistic function

$$ $f(x)=a+\frac{d-a}{1+e^{-b(x-x_{0})}}=a+\frac{d-a}{1+ce^{-bx}},$ (7) $$

where parameters $a,b,c,d$ are responsible for particular features of the logistic function.
Parameters $a$ and $d$ indicate the lower and, respectively, the upper asymptote. Parameter $b$ is the logistic growth rate, and finally, parameter $c=e^{bx_{0}}$ is related to the inflection point $x_{0}$ at which the maximum growth of the function occurs.
To find the best fitting logistic curve we use a standard regression function.
The logistic function is strictly increasing, thus the derivative, which is given by $f^{\prime}(x)=\frac{bc(d-a)e^{-bx}}{(1+ce^{-bx})^{2}}$, is always positive. The derivative firstly increases (from values close to zero), and after reaching its maximum value at the inflection point, it decreases.
To determine the bounds for reaching the learning and generalization phases, we find the values for which the derivative is equal to a given fraction of the maximum possible growth rate. After testing several cases, the results show that the choice of this threshold does not affect the relation between the phases’ boundaries. Therefore, we decided to conduct our analysis for $20\%$ of maximum growth rate.

Figure: (a) CAMeLU on *mini*ImageNet
Refer to caption: extracted/5890138/images/camelumini.png

Figures 7(a) and 7(b) show the results for CAMeLU on the *mini*ImageNet and CUB datasets, respectively.
For *mini*ImageNet, we obtain the approximation function to be $f(x)=0.04+\frac{0.54}{1+9636e^{-0.43x}}$. Moreover, the number of epochs where the learning phase begins is $15$ and the number of epochs where the generalization phase begins is $29$. On the other hand, for CUB dataset, the approximation function is $f(x)=0.01+\frac{0.48}{1+25530e^{-0.47x}}$, and the number of epochs where the following phases begin is $16$ and $28$.

Figures 7(c) and 7(d) show the results for CAML on the *mini*ImageNet and the CUB datasets, respectively. Similarly, we obtain the approximation function for the *mini*ImageNet to be $f(x)=0.06+\frac{0.56}{1+1326e^{-0.25x}}$. and the number of epochs where the learning phase and the generalization phase begin is $18$ and $42$. Finally, for the CUB dataset, the approximation function is $f(x)=-0.07+\frac{0.50}{1+648e^{-0.13x}}$, and the number of epochs where the following phases begin is $29$ and $74$.

Remarkably, CAML requires more training time to reach the generalization phase than CAMeLU. This difference likely arises from CAMeLU’s task creation mechanism, which generates tasks with high cross-task variance. This strategy acts as a form of task augmentation, facilitating quicker generalization to unseen tasks.

### A.9 Limitations

Despite the promising results demonstrated by our novel UML approach on several datasets, some limitations remain. Its applicability and robustness in real-world scenarios with diverse and noisy data remain to be thoroughly evaluated. In real-world applications, data can be incomplete, mislabeled, or drawn from significantly different distributions, leading to potential degradation in the model’s performance in the presence of noisy or corrupted data. Additionally, the feature extractor used in CAMeLU is pre-trained in a supervised manner. While the pre-training dataset is independent of the data seen at inference, replacing it with an extractor pre-trained using an SSL strategy could make the pipeline fully unsupervised, albeit at the price of performance degradation. Lastly, the proposed approach is designed to handle a fixed number of classes (ways) per task during training and testing, requiring knowing the value of $N$ in advance. Modifications to the task creation and training process would be necessary to extend our approach to handle an arbitrary number of ways.

### A.10 Complete results with standard deviations

Table: Table 10: Performance comparison on *mini*ImageNet, CIFAR-fs, CUB, Aircraft, and Meta-iNat datasets for 5-way 1-shot and 5-way 5-shot scenarios. Cross-domain approaches are trained using ImageNet-964 and a ResNet-50 feature extractor. The symbol $\dagger$ indicates results that are affected by data leakage. The bold font highlights the best performing UML approach for each setting. Results show the mean and standard deviations across three complete runs of the algorithms. This table refers to Table 1 in Section 4.3.

Table: Table 11: Accuracy results obtained training PsCo, BECLR, and CAMeLU with a small-scale dataset, namely *mini*ImageNet, denoted as (*mini*) in the table. Results show both in-domain performance (on the test set of *mini*ImageNet) and cross-domain performance on CIFAR-fs, CUB, Aircraft, and Meta-iNat. The mean and standard deviation across three complete runs of the algorithms. This table refers to Table 2 in Section 4.5.

Table: Table 12: Comparison between CAMeLU and SSL approaches for the 5-way 1-shot and 5-way 5-shot scenario on *mini*ImageNet, CIFAR-fs, CUB, Aircraft, and Meta-iNat. The symbol $\dagger$ indicates results that are affected by data leakage. Results show the mean and standard deviations across three complete runs of the algorithms. This table refers to Table 3 in Section 4.6.

## Peer Reviews

confidence: 5
contribution: 3
initial_rating: 6
presentation: 3
questions: One more question:
As the class of instances in FSL are pseudo-labels randomly picked in range $0-N$, how to explain the top linear lay for classification that project the output embedding of the query into the final category distribution? An instance could be of class 0 in task $T_i$ but of class 1 in task $T_{i+1}$, how can the in-context classifier (i.e. the top linear lay) predict its class without finetuning upon the support set?
soundness: 4
strengths: 1) The work proposes a novel pseudo-task creation mechanism to generate FSL tasks out of unsupervised dataset, providing a new (maybe efficient) way to learn from unlabeled data. 
2) Experiments with CAML show that CAMeLU outperforms other unsupervised methods to achieve promising results.
summary: This work aims to tackle few-shot learning (FSL) by learning from unsupervised dataset. It shares a similar idea with CAML[1] in model design by taking FSL as a sequence modeling problem. The instance embedding $f_{\psi}$ and the class encoding $g_{\phi}$ of  
 a support image are contacted to form a "token" in the context. of the sequence, and a transformer encoder learns from the context to generated output feature for the query. The output feature finally is projected by a top linear layer predict the class of the query. 

To learn from the given unsupervised dataset, this work proposes a novel task creation mechanism to generate pseudo-tasks. In each run of the task creation mechanism, $N$ samples are randomly selected from the unsupervised dataset and data augmentation strategies are applied to each sample to generate $K$ instances (which are utilized as the support examples), simulating the $N$-way $K$-shot setting. Query samples in the pseudo-task are generated by mixup the selected sample (and its augmented version) with randomly selected samples in the "background" dataset. 

The pseudo-task creation provides a way to perform meta-learning in the pre-training stage when no labeled dataset is available, which is interesting and instructive.


[1] Fifty, C., Duan, D., Junkins, R. G., Amid, E., Leskovec, J., Re, C., & Thrun, S. Context-Aware Meta-Learning. In The Twelfth International Conference on Learning Representations.
weaknesses: However, I have the following concerns:
1) The model in this work is the same as CAML, which shows limited novelty. 
2) Though the task formulation is interesting, only CAML and its successor (e.g. CAMeLU) are fairly trained in the setting. Other unsupervised method cannot leverage the supervised pseudo-tasks as supervised methods do. Essentially, CAMeLU is a supervised method. The pseudo-task generation provides a way to bridge the unsupervised scenario and the supervised scenario.
3) Instead of providing a specific instance (e.g. CAML) to illustrate how the proposed task generation facilitates FSL from unsupervised dataset. I prefer to see more evidences that showcase the pseudo-task creation is a valid and efficient mechanism that makes supervised method like ProtoNet, MAML, etc, feasible in unsupervised scenario. This, I think, is the core contribution of this work.
4) In experiment, building a new subset of Imagenet-1k (i.e. ImageNet-964) is not necessary since the method is so-called unsupervised. Note that, CLIP and its variants would cause information leakage if not carefully considered, because the texts may explicitly work as anchors to categorize instances belong to the same class together.
5) I donot think it is proper to put experiments on CIFAR-FS into the cross-domain setting, because CIFAR-FS contains natural scene color images as in the miniImagenet. Conventionally, cross-domain setting refers to either transferring from coarse-grained setting to fine-grained setting as in FSL, or transferring from natural scene color image setting to painting image setting where instances from two domains show quite different appearances.
6) Typos: e.g. In A.1 Line 793, the iamge embedding's output size decreases to 768, resulting ....

---

confidence: 2
contribution: 3
initial_rating: 5
presentation: 2
questions: 1. I was wondering if mixup is used during model training, would we still get a reasonable performance in a meta learning setting? 


2. What is the specific justification for the design that was used for the transformer model that is used for experiments? What is the computational overhead that it adds?

3. Metalearning is overcrowded field with so many existing works. What was the reasoning to select methods that were used for comparison? It looks some of these methods are not the most recent methods which likely will have better performance. It is necessary to include 8-10 methods for comparison with majority of them to be most recent works that achieve the highest performances to demonstrate that the proposed method is competitive.
soundness: 3
strengths: 1. The paper is relatively straightforward to read and follow.

2. The performance boost compared to the baselines is significant on all benchmarks.

3. The code is provided and although I did not run it but it looks well documented and easy to run which will make reproducing the results straightforward.
summary: The paper develops CAMeLU for unsupervised meta-learning setting, where the goal is to leverage the in-context learning capabilities of transformers to create transferable feature representations from unlabeled data for new tasks with small numbers of labeled data. By modeling meta-learning as a sequence prediction problem, each observed task is modeled as a sequence of support instances and an unknown query image. The transformer encoder subnetwork then identifies task-specific patterns from support images for that task which enhances accuracy of predictions on query images by making the model specialized for the input task. Data augmentation and task mixing are also used to generate diverse training tasks that challenge the model to improve generalization on new tasks. Experimental results on a benchmark formed from five datasets are offered to demonstrate that CAMeLU is effective for unsupervised meta-learning and leads to a performance close to supervised and self-supervised meta-earning methods.
weaknesses: 1. The model may become very large due to the added transformer model which computationally may become expensive and challenging to handle compared to methods are using only CNN architectures.

2. Comparison is limited to only a few methods, despite the fact meta learning have a rich literature.

3. Analytic experiments are limited and do provide much insight about the proposed method. For example, what are the circumstance and criteria under which the proposed method is more effective? What are the limitations? What is the reason behind the improved performance compared to the baselines?

---

confidence: 5
contribution: 3
initial_rating: 6
presentation: 3
questions: 1.	During the construction of the query set using mixup, does the correlation between the sampled image and the combined augmented image affect the model's performance and stability? For instance, do cases where they belong to the same class or are completely unrelated impact the outcome?

2.	Under time constraints, does the computational cost of this construction method lead to a significant performance improvement in the model?

3.	How sensitive is the model's performance to the parameters used in the query set construction method?
soundness: 2
strengths: 1.	Overcomes the limitation in the UML field of relying solely on simple data augmentation for constructing training tasks, by proposing a novel sequence modeling-based task construction approach.

2.	Effectively leverages the advantages of in-context learning in LLM.

3.	Provides extensive experiments and a thorough hyperparameter tuning process, which comprehensively demonstrate the advantages of the proposed algorithm.
summary: This paper proposes CAMeLU, a novel approach to unsupervised meta-learning (UML) that utilizes transformer architectures' in-context learning capabilities to extract contextual information from support samples and perform predictions on query data as a sequence modeling task.
weaknesses: 1.	Lacks an explanation of the benefits of combining transformer architecture with the proposed data construction method, and does not clarify whether other architectures could also be adapted. In short, there is insufficient discussion of the model's generalizability.

2.	Lacks detailed descriptions of the fixed feature extractor f and the learned class encoder g.

---

confidence: 3
contribution: 2
initial_rating: 5
presentation: 3
questions: * What are the training costs for CAMeLU? When constructing tasks from unlabeled datasets, especially when using a mixup strategy, do the hyperparameters need to be carefully tuned?

* The comparison with CAML in Figure 3. Why doesn't CAML show an improvement in relative validation accuracy during training? What could be the reason for this?
soundness: 3
strengths: * The authors propose a novel task creation mechanism that generates diverse few-shot tasks from unlabeled datasets through a combination of data augmentations and a mixing strategy. This seems reasonable.

* They utilize the transformer’s in-context learning capability, eliminating the need for fine-tuning to specific test domains, which is commendable.

* The experiments are thorough, and the exploration shows that the model achieved generalization.
summary: This paper reframes meta-learning as a sequence modeling problem, allowing the transformer encoder to learn task context from support images and use it to predict query images. The core is a mechanism for generating diverse tasks using a combination of data augmentations and a mixing strategy. Experimental results demonstrate the superiority over existing unsupervised meta-learning baselines, highlighting the efficacy of the model in leveraging generalization over memorization.
weaknesses: * The comparisons in the experiments may not be entirely fair. For instance, differences in model architecture between methods, and whether additional feature extractors or class encoders were used, should be noted in a table to enable clearer comparisons. To my knowledge, this seems somewhat unfair to the in-domain baselines. It would be appreciated if a table showing the parameter count and computational overhead for each method were included.

* In comparison to CAML, another transformer-based in-context learning method, or SSL methods, CAMeLU doesn’t perform as well.

Meta-review: This work addresses the challenge of few-shot learning (FSL) by leveraging an unsupervised dataset. It adopts a similar approach to CAML [1] in its model design, framing FSL as a sequence modeling problem. This allows the transformer encoder to learn task context from support images and utilize it to predict query images. To effectively learn from an unsupervised dataset, the authors propose a novel task creation mechanism that combines data augmentation with a mixing strategy to generate pseudo-tasks. Experimental results demonstrate significant improvements over existing unsupervised meta-learning baselines, underscoring the model's ability to generalize effectively rather than rely on memorization.

All reviewers agreed that the pseudo-task creation mechanism is both novel and promising, with the empirical results showing extensive and significant improvements that validate its effectiveness.

Given the potential impact of this work on the meta-learning and few-shot learning communities, I recommend its acceptance.

Decision: Accept (Poster)