{'fraction_non_alphanumeric': 0.03328696971612822, 'fraction_numerical': 0.011285325915154581, 'mean_word_length': 5.042979942693409, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Exploiting Both Domain-specific and Invariant Knowledge via a Win-win Transformer for Unsupervised Domain Adaptation

Unsupervised Domain Adaptation (UDA) aims to transfer knowledge from a labeled source domain to an unlabeled target domain. Most existing UDA approaches enable knowledge transfer via learning domain-invariant representation and sharing one classifier across two domains. However, ignoring the domain-specific information that are related to the task, and forcing a unified classifier to fit both domains will limit the feature expressiveness in each domain. In this paper, by observing that the Transformer architecture with comparable parameters can generate more transferable representations than CNN counterparts, we propose a Win-Win TRansformer framework (WinTR) that separately explores the domain-specific knowledge for each domain and meanwhile interchanges cross-domain knowledge. Specifically, we learn two different mappings using two individual classification tokens in the Transformer, and design for each one a domain-specific classifier. The cross-domain knowledge is transferred via source guided label refinement and single-sided feature alignment with respect to source or target, which keeps the integrity of domain-specific information. Extensive experiments on three benchmark datasets show that our method outperforms the state-of-the-art UDA methods, validating the effectiveness of exploiting both domain-specific and invariant


Introduction
It is well known that deep neural networks are datahungry [22,49] and hard to generalize to test data sampled from a different distribution. Therefore, despite that they have achieved remarkable success on multiple computer vision tasks such as image classification [22], object detection [46] and semantic segmentation [6], their real-world utility is often limited. To address these practical issues, unsupervised domain adaptation (UDA) is proposed, aiming to transfer knowledge from a labeled source domain to another unlabeled target domain with the presence of domain shift [2,42] in data distribution.
Over the past decade, researchers have made great effort to improve the performance on UDA. Following the guidance of the theory [1], most works adopt a similar paradigm that learns to extract domain-invariant representations from the encoder and reuse the source classifier on top of that. In vision tasks, the basic architecture of the encoder is usually a convolution-based neural network such as VGG [49] and ResNet [22]. Domain-invariant representations are learned via the domain alignment process, which is either explicit (e.g. minimizing certain statistical metrics [38,40,50] or confusing the domain discriminator [17,39]) or implicit (like self-training [35,61,65] or target-oriented data augmentation [32]). However, due to lacking of true label supervision in the target domain, the class-discriminative information is easily lost during domain alignment [9], and the source classifier still inevitably biases to the source domain [35], damaging the effectiveness of knowledge transfer. We generally interpret these problems as a dilemma between exploring the knowledge from its own domain and acquiring the knowledge transferred from the other domain. Such a dilemma leads to the following question: can one develop a win-win solution for in-domain knowledge preservation and cross-domain knowledge transfer in UDA?
Solution to the question above may come with vision Transformers. Recently, the rise of Transformer in vision tasks shows the potential of pure attention-based models. One prominent difference of these models is that they abandon the strong inductive bias hard-coded in the convolutional neural networks (CNNs) [14,64]. The inductive bias in the form of locality and spacial invariance makes convolution-based models more sample-efficient and parameter-efficient and achieve strong performances [14], yet it has certain limitations in learning the cross-domain transferable representation. For instance, the local convolution operation intermixes the task-related content information with task-irrelevant style information such as the background color, making the high-level representation captured by CNN affected by task-irrelevant styles [31]. Transformers, on the other hand, do not confined to these restrictions and thus learns more transferable representations [64]. As shown in Fig. 1, we empirically observe that CNN models pretrained on source domain pay attention to the wrong place in the target images more easily, especially under large domain gap (e.g., Ar→Cl in Office-Home), and their performances on target domain are far behind their vision Transformer counterparts which have tantamount network parameters and classification accuracy on ImageNet [15].
Another intriguing property of vision Transformer lies in its flexibility of appending learnable classification tokens that serve for different purposes. Previous UDA methods generally reuse the source classifier for target prediction on top of a shared feature representation. Ideally, the features of the two domains can be perfectly aligned class-wisely and the classifier can make accurate predictions on target domain. However, due to the difficulty of perfect alignment in practice, such paradigm raises a competition.
On the feature level, the alignment encourages crossdomain knowledge sharing and suppresses domain-specific information. Yet on the classifier level, the source classifier explores source-specific knowledge for minimizing source classification loss. Some recent works make efforts to balance the two sides [55,56], but they are still confined to the paradigm. In this paper, we make an attempt on exploring a new possibility of handling both part of the knowledge. Inspired by DeiT [52] that two tokens converge to towards different vectors when trained on different objectives, adopting two tokens that respectively learn the source-oriented and target-oriented representations (or tokens) seems to be a reasonable choice. Accordingly, two classifiers instead of one can be utilized to match different tokens.
Based on these considerations, we propose in this paper a Transformer-based UDA framework dubbed as win-win Transformer to simultaneously exploit domain-specific and invariant knowledge. We adopt two classification tokens [src] and [tgt] that learns different mappings, and build on top of each one a domain-specific classifier. To maximally preserve the domain-specific information, we let the two classifiers learn from labels or pseudo-labels in their own domain respectively, and add attention masks to the selfattention operation to prevent the two classification tokens from intervening each other. To achieve knowledge transfer across source and target domain for mutual enhancement, we propose two cross-domain transfer mechanism: the target pseudo-label refinement mechanism using source structural information and the bi-direction regularization mechanism using the discriminative information. We empirically choose the weighted K-means clustering [34] and the supervised contrastive learning [26] as the practical implementation while showing other variants also feasible in § 4.4.
In general, we highlight our three-fold contributions.
• We set up a new transformer-based UDA framework that has two classification tokens for learning different domain-oriented representations and two domainspecific classifiers to fully explore domain-specific knowledge without mutual interference between the two domains.
• We propose the source guided label refinement to transfer source structural information to target domain and conduct single-sided feature alignment in both directions through contrastive learning with stopgradient operation.
• Our method achieves the state-of-the-art performance on three benchmark UDA datasets, which might shed light on future researches on addressing transfer learning problems using vision transformers.

Unsupervised Domain Adaptation (UDA)
To address the performance degradation issue when deploying models to new environments, UDA is proposed and widely studied [42], which aims to train a model that can adapt from labeled source domain to unlabeled target domain. The mainstream of UDA methods focuses on learning domain-invariant representations and reuserd the source classifier. Statistical metrics such as maximum mean discrepancy (MMD) [20] between source and target domain are proposed as objectives for models to minimize [29,38,40]. Other approaches find inspiration from adversarial training [19] and thus capture domain-invariant representations via a min-max game with the domain discriminator. For example, DANN [18] introduces a gradient reversal layer to enable simultaneous optimization of the two players. CDAN [39] brings class conditional information to the discriminator, GVB [13] adds "gradually vanishing bridges" to promote alignment and RADA [24] reenergizes the discriminator using dynamic domain labels.
Another line of researches borrows the pseudo-labeling idea from semi-supervised learning [28], where the reliable model predictions on unlabeled data are chosen as pseudo-labels to assist the model retraining. Most UDA approaches [7,57,65] adopt target pseudo-labels for a better conditional distribution alignment, such as CBST [65] and MSTN [57]. To obtain less noisy pseudo labels, SHOT [34] and ATDOC [35] consider the structural information of target data to refine the original labels. These methods can be regarded as conducting implicit domain alignment by making the source and target features of the same class similar, and also adapt the source classifier to be more targetspecific. The combination of the two parts of knowledge makes the pseudo-labeling based UDA achieve promising results. However, these works train both source and target data on the same classifier, which might damage the domain-specific information for both domains. Our method, on the other hand, individually trains two classifiers using data from the respective domain to maximally preserve domain-specific knowledge.
Recently, some works start to pay more attention to domain-specific information learning [4,31,47]. To model domain discriminative representation separately, DSBN [4] introduces a domain-specific batch normalization mechanism. GDCAN [31] designs a domain conditional attention module in convolutional layers to activate distinctly interested channels for each domain, while DWT [47] makes the domain-specific whitening transform at higher layers. Different from them, our method takes the advantage of Transformer architectures to separately explore source-specific and target-specific knowledge.

Vision Transformers
Motivated by the significant improvements of Transformers on natural language processing (NLP) tasks, researchers begin to apply Transformer architectures to computer vision (CV) as a potential alternative for CNN backbones. ViT [16] proposes to apply a Transformer model with image patches as inputs to solve image classification problems. Its competitive results compared to CNN backbones encourages further explorations on attention-based networks in CV. Later, DeiT [52] introduces a distillation token with more training strategies that enables ViT to train on much smaller datasets. Recent works such as Swin Transformer [37], PVT [54] and CrossViT [5] improve architec-ture from different aspects. Furthermore, other researchers apply vision transformers to downstream tasks like semantic segmentation [60,62], object detection [3,51] and multimodal tasks [23]. Meanwhile, more detailed comparisons between vision Transformer and CNNs are investigated to show their relative strength and weakness [10,14,45,64].
Since Transformer has the intrinsic advantages to extract more transferable representations, several works [58,59] have been proposed to solve domain adaptation with it. For instance, TransDA [59] injects an attention module after the CNN-type feature extractor to guide the model attention in source-free DA. CDTrans [58] adopts the complete transformer architecture and introduces a cross-attention mechanism between the selected source-target pairs. The outputs of the cross-attention branch are then used to supervise the target self-attention branch. We take a different perspective from these methods by noticing that the classification tokens in vision Transformers is capable of learning different mappings, hence is desirable for preserving domain-specific knowledge. Therefore, we propose to train a transformer with two classification tokens to both exploit in-and crossdomain knowledge for extracting better representations.

Win-win Transformer
This section we introduce our win-win Transformer framework in detail. Our key notion of win-win is mainly reflected in that the proposed framework allows the learned representation to benefit from both in-domain and crossdomain knowledge, without leading to a zero-sum competition that either losses crucial domain-specific information or leads to domain misalignment.

Preliminaries
We begin by introducing the notations in UDA and the self-attention mechanism in vision Transformers. Data in UDA are sampled from two different distributions P s and P t to create a labeled source domain and an unlabeled target domain D t = {x tj } nt j=1 , where n s and n t denote the number of sampled data. The goal of UDA methods is to utilize these data to train a model that performs well on the target domain. While most prior methods extract feature representations from data using convolution-based models, this work turns to fully attention-based vision Transformer to learn embeddings that can simultaneously benefit from in-domain and cross-domain knowledge.
Self-attention mechanism is at the core of vision Transformers [16]. Given a sequence of input features X ∈ R N ×D , three learnable linear projectors W Q , W K , W V are applied on the layer-normalized features of it separately to obtain the queries Q ∈ R N ×d , the keys K ∈ R N ×d and the values V ∈ R N ×d . The query sequence is then matched against the keys using inner products to get the N × N at- tention matrix whose elements represent the semantic relevance of the query-key pairs in the corresponding position. The output of the self-attention is the weighted sum of the values, determined according to the attention matrix: Self-attention can be viewed as a feature aggregation for each position, using transformed features from other strongly correlated positions. This allows the Transformer to jump out of the inductive bias of locality and incorporate more global information [45]. The output of the selfattention is combined with the original input through residual connection and further passes through a feed-forward network (FFN), which completes a full self-attention module in vision Transformer.

In-domain Knowledge Exploration with Two Classification Tokens
The main idea of in-domain knowledge exploration is to enable the model to learn domain-specific information. Formally, for each input sequence of image features from image patches Since we prefer the two tokens to learn different mappings that respectively contains more domain-specific information for source and target, we design a domain-wise token mask to prevent the two token from aggregating each other's feature. Specifically, we define an N ×N mask matrix with values at bottom-left and top-right corners equal to negative infinity, which will then become zero after the Softmax function: Then the mask is applied in each self-attention module, thus substituting the Attention formula in Eq. (1) by the following MaskedAttn.
The feature sequence will forward propagate to the last layer of the vision Transformer, and we utilize the two features that corresponds to the classification tokens. The source and target feature generated from the source token (source-oriented) are denoted as f s si = f s (x si ), f s tj = f s (x tj ), and that from the target token (target-oriented) as Next, we build a sourcespecific classifier g s and a target-specific classifier g t to separately proceed features f s and f t . Then, the ground truth source label is adopted on g s to explore the source-specific knowledge: where E(·, ·) denotes the standard cross-entropy (CE) loss, and g s si = g s • f s (x si ) is the logit output. Similarly, the target-specific classifier and the target-oriented representation are supervised by the target CE loss, using pseudolabels in the target domain: Here,ỹ tj is the hard pseudo-label for x tj and g t tj = g t • f t (x tj ). We will further discuss how to obtain it in the next section. It's worth noting that different from ATDOC [35] which regards a nonparametric model as the auxiliary target classifier to obtain pseudo-labels for training the main linear classifier, our target classifier is directly trained for target domain classification.
To this end, we replace the traditional shared classifier with two domain-specific classifiers trained on different loss functions. Nevertheless, training a classifier with only target pseudo-labels could be problematic. Hence, it needs information from source domain for correction, and meanwhile an effective way to transfer cross-domain knowledge is demanded. We address these issues by utilizing the "byproducts" in the process, i.e. the source-viewed target features and target-viewed source features.

Bi-direction Cross-domain Knowledge Transfer
Target pseudo-label refinement incorporating source structural information. Since target pseudo-label is the only information to supervise the target-specific classifier, its noise must be maximally suppressed. We address this by using the structural information, that features in the neighborhood are likely to have the same label, to refine the original pseudo-labels which are based on predictions. The key point here is that we discover that better refinement results are achieved using source-oriented representation instead of the target-oriented one. Our hypothesis is that the sourceoriented representation is supervised by clean source labels, which preserves finer structural relationships between feature points. On the other hand, the target-oriented representation is prone to overfit on mislabeled data which damages the structural information. Therefore, by refining target pseudo-labels on source-oriented representations, we remedy the problem through source knowledge. The results of a comparison study are shown in § 4.4.
Empirically, we adopt a simplified version of the previously proposed weighted K-means method [34], which achieves superior performance especially when the number of categories is large. The class centers are calculated as a weighted sum over all (source-oriented) target features f s tj , and the refined pseudo-labels are obtained by finding the nearest class center: , y tj = arg min k d(g s tj , c k ).
The function d(·, ·) denotes the cosine distance between the two vectors. The label refinement process starts at the very beginning and is repeated with a fixed interval until the network converges. So far, the source-oriented representation has not yet received any information about the target domain. To enhance its generalization performance on target data without damaging its source-specific information, we propose to conduct feature-level alignment between f s s and f s t with a stop-gradient operation on the former one. This is inspired by works in self-supervised learning [8,21] where they use stop-gradient to avoid model collapse. In our case, we expect to keep f s s still and bring f s t closer towards it to transfer target domain knowledge. MMD [20], MSTN [57] and contrastive learning with label information [26] are selected as candidates, and we empirically find that contrastive learning prevails. Specifically, given each target sample x t with pseudo-labelỹ t , we have positive source samples x + s with the same class label and other negative source samples, and we optimize the following loss Loss L con s is combined with cross-entropy loss L s to train the source classifier and [src] token. With the help of target knowledge, the label refinement in Eq. (6) obtains less noisy target pseudo-labels that will benefit the target classifier in return.
Target self-training regularization using source discriminative information. To further transfer the source knowledge to promote target representation learning, we adopt a symmetric form of Eq. (7) on f t t and f t s : where x + t are positive target samples that have the same (pseudo) labels as x s does. Note that this time we stop the gradient from f t t . The overall formulation of our objective function is the sum of four losses with only one trade-off parameter λ:

Datasets and Setup
We test and analyze our proposed method on three benchmark datasets in UDA, that is Office-Home [53], VisDA-2017 [44] and DomainNet [43]. Detailed descriptions can be found in the supplementary. Note that except for special announcement, all the reported target accuracies are from the target classifier g t .

Implementation Details
Our method is based on the two-token version of DeiT-Small(S) and DeiT-Base(S) [52] backbone pretrained on ImageNet-1k [15]. We set the base learning rate as 3e-3 on VisDA2017 and DomainNet and 3e-4 on Office-Home, while both randomly initialized classifiers have a 10 times larger learning rate following [39]. The training process is optimized by Stochastic Gradient Descent (SGD) with momentum 0.9 and weight decay 1e-3. The batch-size is 32 for both domains. We adopt the source pretrained model to obtain the initial target pseudo-labels. The trade-off param-eters λ and the temperature τ are set as 1.0 and 0.1 respectively for all datasets.

Overall Results
We adopt DeiT-S/B as the backbones of our method and compare various UDA methods in the experiments. As most of the convolution-based methods use ResNet-50 as their backbones on Office-Home and DomainNet, we report results using DeiT-S of similar sizes on the two benchmarks for a fair comparison and put the results with DeiT-B in the supplementary. For VisDA-2017, both results on DeiT-S/B are reported to compare with ResNet101 backbone.
The results on VisDA-2017 and Office-Home are reported in Table 1,2. First, we notice that the source model DeiT-S surpasses ResNet-101 by 14.3% on VisDA-2017 and ResNet-50 by 9.7% on Office-Home, which shows the superiority of vision Transformers on UDA. Nevertheless, its performance is still way below the convolution-based UDA method, making it necessary to design suitable algorithms to make full use of Transformers. Second, WinTR-B achieves a class average accuracy of 90.1% which out- Table 3. Accuracy (%) on DomainNet for unsupervised domain adaption. In each sub-table, the column-wise domains are selected as the source domain and the row-wise domains are selected as the target domain.
ResNet50 [22] clp inf pnt qdr rel skt Avg. MCD [48] clp inf pnt qdr rel skt Avg. CDAN [39]   performs all the baseline methods on VisDA-2017, and WinTR-S surpasses ATDOC-NA by an average of 5.0% on Office-Home. The significant accuracy boost validates the effectiveness of our method.
The results on DomainNet is reported in Table 3, where strong results prove our effectiveness when meeting more challenging transfer tasks and unseen target test data. Clearly, we observe that WinTR-S obtains a significant 13.4% average accuracy boost over SCDA and a 9.6% increase over CDTrans. Moreover, our method achieves satisfying results when adapted to Real images, achieving an average of 60.3% accuracy. We hope these promising results on DomainNet would encourage future works to further push the limits of UDA methods on harder benchmarks.

Insight Analysis
In this section, we carry out experiments to fully investigate the influence of each component in our win-win Transformer framework. All the analytical experiments are based on the DeiT-S backbone.
Domain-specific Knowledge Learning. To show that the two tokens in our method preserve more domainspecific information than traditional framework does, we examine the cosine similarity between source-oriented rep-resentation f s tj and target-oriented representation f t tj for each target sample. We compare our method with two variants: a) optimizing both classifiers with the same loss L s + L t , b) replacing the two classifiers by one common classifier trained by L s + L t . The results of the similarity score for all target samples are shown in Fig. 3(a). We find that more target samples obtain divergent representations on the two tokens under our proposed separate training framework, indicating that they learn different perspectives.
Ablation Study. To examine the influence of components on the final performance, we respectively remove the domain-wise token mask and contrastive losses. The results are listed in Table 4. It can be found that each component contributes to our method, especially on harder transfer tasks that need to exploit more knowledge of both indomain and cross-domain. We also note that the mask plays an important role by preventing the two tokens from interfering with each other.
Sensitivity Analysis. To show that our method is robust to different choices on hyperparameter λ and τ , we vary their values on two randomly selected Office-Home tasks and show the results in Fig. 3(b) and (c). Expect for setting λ = 0 where the contrastive loss is aborted, our method maintains stable accuracies in spite of the parameter change.  .97 0.975 0.98 0.985 0.99 0.995 1 Alternatives for Label Refinement and Knowledge Transfer Methods. The proposed WinTR could be a general framework with multiple options. We conduct experiments on different alternatives for the label refinement and knowledge transfer in our method.
The alternatives (including ours) for label refinement that utilize structural information in the feature space are: K-Nearest Neighbor (KNN) [35], where the label of a target sample is determined by its nearest K samples in the feature space. Here we set the hyperparameter K = 5. Kmeans [34], which is adopted and described in our method.
The alternatives for knowledge transfer that aligns the source and target features for each domain-oriented representation are: Maximum Mean Discrepancy (MMD) [20], MSTN [57] that aligns the source feature center with the target feature center of the same class and Contrastive inspired by [26], which is described in our method. Note that we keep the stop-grad operation on f s s and f t t for each knowledge transfer method to maintain the integrity of the two domain-oriented representations.
Contrastive-based Knowledge Transfer Improves Generalization. Here we further investigate the effect of the contrastive-based knowledge transfer. We test target data on source-specific classifier, (i.e. g s (X t )) and vise versa. Note that in this experiment, the test data comes from the other domain and is never trained on the classifier being tested. As shown in Fig. 3(d), after applying both contrastive losses (denote as w/ L con ), the prediction accuracies on unseen data from the other domain improve significantly, verifying that the cross-domain knowledge transfer learns better feature embeddings than only conducting indomain knowledge exploration. Which Representation for Label Refinement? To prove that the label refinement process achieves better results when utilizing source-oriented representation instead of target-oriented ones, we compare the two variants on several tasks in Office-Home and VisDA-2017. Specifically, we employ the same label refinement method on f s t and f t t respectively and use the obtained pseudo-labels for model training. The results are listed in Table. 6, which indicates that source-oriented representation is more suitable, especially for harder transfer tasks like Pr→Cl when pseudolabels before refinement are noisier.

Conclusion
We propose a win-win Transformer framework for UDA. Different from the classical UDA paradigm that learns a domain-invariant representation and reuses the source classifier to predict target, we propose to separately train two mappings and two domain-specific classifiers via [src] and [tgt] token. The new framework enables a simultaneous exploitation of domain-specific and invariant knowledge without interfering with each other. We propose two mechanisms to conduct cross-domain knowledge transfer between the two tokens while training the two classifiers with different objectives. Extensive experiments on three benchmarks prove the effectiveness of our method.

Training Algorithm of WinTR
We show in this section the overall training procedure of our proposed WinTR. As shown in Algorithm 1, we first train a source model from the ImageNet-pretrained DeiT to obtain the initial target pseudo-labels for each target sample (Stage 1). Then we Reinitialize the backbone along with two new classifiers. Four losses are computed and the model is optimized. After certain rounds of training, the target pseudo-labels are updated using new features and predictions. This process continues until the model converges or the max iteration is reached (stage 2). Obtain f s and f t from the Transformer backbone; 7: Compute Ls by Eq. (4) with source classifier g s and ysi; Accumulate the above losses and optimize the model; 12: For each xtj, obtain new pseudo-labelỹtj using Eq. (6); 13: end for

Experimental details
Three benchmarks in UDA that is used in our experiment are Office-Home, VisDA-2017 and DomainNet.
Office-Home [53] is a standard dataset for DA which contains four different domains: Artistic(Ar), Clip Art(Cl), Product(Pr) and Real-world(Re). Each domain consists of 65 object categories found typically in office and home scenarios.
VisDA-2017 [44] is a 12-class UDA classification dataset for cross-domain tasks from synthetic(S) to real(R). Among them, the training set incorporates 152,397 synthetic images and the validation set contains 55,388 realworld images collected from Microsoft COCO [36].
In the training procedure, we adopt similar dataaugmentation techniques such as Rand-Augment [11] and random erasing [63] to fully utilize the limited training data as in DeiT. We find these data-augmentations very helpful for training Transformers in UDA tasks.

Additional Experimental Results on Domain-Net Dataset
In this section, we report the complete results of our method on DomainNet, including WinTR-S and WinTR-B, and compare them to other baseline methods. The results are shown in Table 7 in the next page. We can conclude that WinTR achieves superior performance on DomainNet benchmark, reaching an average accuracy of 46.8% using WinTR-B which is 12.2% higher than its backbone DeiT-B. Also, WinTR-S already outperforms CDTrans-B by an average of 4.8% as well as all the UDA methods that are based on ResNet-50 backbone. These results validate the effectiveness of our method, proving that training an individual target classifier using only target data and pseudolabels is applicable when using a Transformer as backbone. This success might lead to the rethinking of sharing a common classifier for both source and target domain. Table 7. Complete table of accuracy (%) results on DomainNet for unsupervised domain adaption. In each sub-table, the column-wise domains are selected as the source domain and the row-wise domains are selected as the target domain. Methods from the first two rows are based on ResNet-50 backbone, while the methods from the last two rows are based on DeiT-Small/Base architectures.