Tracing Representation Progression: Analyzing and Enhancing Layer-Wise Similarity

## Abstract

Abstract Analyzing the similarity of internal representations within and across different models has been an important technique for understanding the behavior of deep neural networks. Most existing methods for analyzing the similarity between representations of high dimensions, such as those based on Canonical Correlation Analysis (CCA) and widely used Centered Kernel Alignment (CKA), rely on statistical properties of the representations for a set of data points. In this paper, we focus on transformer models and study the similarity of representations between the hidden layers of individual transformers. In this context, we show that a simple sample-wise cosine similarity metric is capable of capturing the similarity and aligns with the complicated CKA. Our experimental results on common transformers reveal that representations across layers are positively correlated, albeit the similarity decreases when layers are far apart. We then propose an aligned training approach to enhance the similarity between internal representations, with trained models that enjoy the following properties: (1) the last-layer classifier can be directly applied right after any hidden layers, yielding intermediate layer accuracies much higher than those under standard training, (2) the layer-wise accuracies monotonically increase and reveal the minimal depth needed for the given task, (3) when served as multi-exit models, they achieve on-par performance with standard multi-exit architectures which consist of additional classifiers designed for early exiting in shallow layers. To our knowledge, our work is the first to show that one common classifier is sufficient for multi-exit models. We conduct experiments on both vision and NLP tasks to demonstrate the performance of the proposed aligned training.

## 1 Introduction

As one of the most significant breakthroughs in deep neural network (DNN) architectures developed in recent years, the transformer model [] has driven recent advances in various vision and NLP tasks, such as vision transformer for image classification [] and image generation [, , ], BERT [], GPT [], and other various large language models (LLMs) [] for natural language understanding and generation. It has been viewed as a promising foundation model that can be adapted and extended to various applications and domains []. Additionally, researchers have found that increasing the size (by stacking more layers and/or making them wider) can consistently improve performance, resulting in models of significant size (e.g., the 175B-parameter GPT-3 and the 540B-parameter PaLM). However, the ever-increasing size has posed a significant challenge in studying and understanding exactly how these models solve tasks and in efficiently deploying them.

Given the success of deep learning models, attributed to their ability to learn increasingly complex internal representations as they go deeper through their layers, a promising direction for understanding these models is to study the hierarchical feature learning across layers. Recent work [, , , , ] have uncovered an
intriguing phenomenon regarding the last-layer features and
classifier of DNNs, called Neural Collapse (NC), across many different datasets and model architectures. Roughly speaking, NC refers to a training phenomenon in which the last-layer features from the same class
become nearly identical, while those from different classes become maximally linearly separable. Beyond the last-layer features, recent studies have also shown that deep classifiers progressively compress within-class features while enhancing the discrimination of between-class features from shallow to deep layers [, , ]. Another line of work attempts to compare the representations within and across DNNs. Various approaches have been proposed to quantify the representation similarity, such as the Canonical Correlation Analysis(CCA) [], Centered Kernel Alignment (CKA) [], Orthogonal Procrustes Transformation(OPT)  [] and Pointwise Normalized Kernel Alignment (PNKA) []. Representation similarity analysis has also been widely used in computational psychology and neuroscience as well [, ].

As these approaches are designed to be invariant to certain transformations (such as orthogonal transformation) and can be applied to features with possibly different dimensions, they rely on statistical properties of the representations for a set of data points. For instance, the NC analysis captures the variance of the features from each class, while the widely used CKA for representation analysis replies on the inter-example structures; see Section 2 for the detailed definition of CKA. Consequently, it has been observed that CKA is sensitive to outliers and may
give unexpected or counter-intuitive results in certain situations [].

Figure: ((a))
Refer to caption: extracted/5681537/figures/Introduction/features_deit-small_cifar10_standard.png

### Contribution

In this work, we focus on transformer models, which have particular properties compared to other architectures: a transformer contains identical blocks with residual connections in each block. Thus, the features in a transformer model have the same dimension and may exhibit less rotation difference across layers. Motivated by this observation, we study the layer-wise representation similarity for transformer models on a per-sample basis, allowing us to directly apply the last-layer classifier right after any hidden layer for classification or text generation tasks. This enables an effortless multi-exit model that allows early exit during inference, thereby saving computation time. Our contributions can be summarized as follows.

- •
Layer-wise representational similarity can be captured by cosine similarity We first introduce a straightforward yet efficient sample-wise cosine similarity metric to examine the similarity of internal representations in transformers. Experiments show that the cosine similarity aligns with CKA, which is based on statistical properties of all the features, and is sufficient to reflect the layer-wise representation similarity. This explains the benefit of residual connections in resulting in smoother transitions between layers and potentially leading to more stable feature representations throughout the network. In addition, as illustrated in Figure 1 (a,c), our experimental results on common transformers show that representations across layers exhibit a positive correlation, with similarity increasing as layers become closer. This suggests that the last-layer classifier can be directly applied right after any hidden layers for decision-making, indicating that a transformer is inherently a multi-exit model. Figure 1 (c) illustrates the monotonic increase in layer-wise accuracy.
- •
Aligned training for enhancing layer-wise representation similarity To enhance performance when serving as a multi-exit model, we propose an aligned training method to improve the effectiveness of shallow layers by increasing the similarity of internal representations between different layers. Motivated by the NC phenomenon, where features from the last-hidden layers align with the common classifier, our aligned training approach deploys the common classifier to each layer and then minimizes the average of the cross-entropy losses from all the layers. As shown in Figure 1(b,d), the aligned training can substantially enhance layer-wise representation similarity, thereby improving layer-wise accuracies. Consequently, the aligned training method can help identify the minimal number of layers needed by unleashing the power of shallow layers to transform features faster towards classifier across layers and push the redundancy behind.
- •
Multi-exit models with a single classifier Another important application of the proposed aligned training is to improve the inference efficiency of large models. During inference, the model can be directly deployed on multiple devices with varying memory sizes and computational budget constraints by selecting the appropriate number of layers from shallow to deep. In addition, the model allows early exit to save computation time. Previous works [, , ] design multi-exit models by introducing different classifiers to each layer, which may substantially increase the model size for a large number of classes, such as ImageNet with 1000 classes and GPT3 [] with a vocabulary of $50,257$ tokens. Instead of using separate classifiers for each exit, our multi-exit model employs a common classifier, which to our knowledge is the first of its kind, maintaining the early exit capability and achieving performance on par with models that use multiple classifiers.
We also demonstrate the performance of the proposed aligned training method in fine-tuning LLMs in NLP tasks, including fine-tuning BERT for text classification tasks on the General Language Understanding Evaluation (GLUE) benchmark [] , and GPT2 model for text generation on the Wikitext-103 dataset [].

When preparing this submission, we notice concurrent work [, ] that exploits representation similarity across layers for pruning redundant layers; layers with high similarity in input and output are viewed as redundant and are pruned. However, these methods do not aim to enhance the feature similarity structure. In contrast, our approach improves feature similarity during training, leading to more redundant layers that are primarily located in the deeper layers. The MatFormer  [] introduces a nested structure into the Transformer by jointly training all submodels of different widths. In contrast, our method jointly trains submodels with varying layers. Exploring the potential integration of these approaches will be a focus of future research. While we mainly focus on transformer models, the proposed aligned training can be applied to other deep architectures, provided they have the same dimensions in each layer. Extending the proposed training approach to accommodate varied feature dimensions is the subject of future work.

## 2 Measuring Layer-wise Representational Similarity in Transformer

The transformer architecture [] has driven recent advances in various NLP and vision tasks, and is viewed as a promising foundation model that can be adapted and extended to various applications and domains []. A standard transformer contains $L$ identical blocks, where each block is a sequence-to-sequence function mapping from $\mathbb{R}^{d\times n}$ to $\mathbb{R}^{d\times n}$ that mainly comprises two complementary stages of data transformation: the Multi-head Self-Attention (MSA) across tokens and the Multilayer Perceptron (MLP) layer across features, both with normalization and a residual connection. To briefly illustrate the mechanics, denote by $\boldsymbol{z}^{\ell}$ the set of $d$-dimensional embeddings of $n$ tokens (such as words or image patches) at the $\ell$-th block. The tokens are processed in the transformer as

$$ $\displaystyle\boldsymbol{z}^{\ell+1/2}=\text{MSA}(\text{LN}(\boldsymbol{z}^{ \ell}))+\boldsymbol{z}^{\ell},\quad\boldsymbol{z}^{\ell+1}=\text{MLP}(\text{LN }(\boldsymbol{z}^{\ell+1/2}))+\boldsymbol{z}^{\ell+1/2},$ (1) $$

where LN denotes the layer-wise normalization. Predictions are typically based on the representation or feature of a specific token after $L$ transformations as described in (1). For instance, auto-regressive based LLM (such as GPT) uses the representation of the last token to predict the next word, while ViT uses the representation of a class token [CLS] to classify the image. Consequently, we will focus on the feature (or representation) of this particular token, denoted by $\boldsymbol{h}^{\ell}$ at the $\ell$-th layer. In this section, our goal is to understand how the features are progressively changed within a transformer by analyzing the similarity of internal representations from different layers.

### Existing work on measuring representational similarity

Similarity analysis is widely applied in the literature, including research on learning dynamics [, ], effects of width and depth  [], differences between supervised and unsupervised models [], robustness [, ], evaluating knowledge distillation  [], language representation  [], and generalizability  [, , ].
To enable measuring the similarity of features from from different architectures or layers that have different dimension, most existing methods for analyzing the similarity between representations of high dimensions, such as those based on Canonical Correlation Analysis (CCA) and widely used Centered Kernel Alignment (CKA) [] , rely on statistical properties of the representations for a set of data points. For instance, with $\boldsymbol{H}^{\ell}=\begin{bmatrix}\boldsymbol{h}_{1}^{\ell}&\cdots&
\boldsymbol{h}_{N}^{\ell}\end{bmatrix}\in\mathbb{R}^{d\times N}$ denoting the features $N$ training samples, the widely-used CKA with a linear kernel quantifies similarities between features $\boldsymbol{H}^{\ell}$ and $\boldsymbol{H}^{\ell^{\prime}}$ as

$$ $\operatorname{CKA}=\operatorname{trace}((\boldsymbol{H}^{\ell^{\prime}})^{\top }\boldsymbol{H}^{\ell^{\prime}}\cdot(\boldsymbol{H}^{\ell})^{\top}\boldsymbol{ H}^{\ell})/(\big{\|}\boldsymbol{H}^{\ell}(\boldsymbol{H}^{\ell})^{\top}\big{\| }_{F}\big{\|}\boldsymbol{H}^{\ell^{\prime}}(\boldsymbol{H}^{\ell^{\prime}})^{ \top}\big{\|}_{F}).$ (2) $$

CKA relies on the similarity of inter-example structures since the gram matrix $(\boldsymbol{H}^{\ell})^{\top}\boldsymbol{H}^{\ell}\in\mathbb{R}^{N\times N}$ captures the pair-wise similarity of different samples, focusing on the consistency of relative positions among features.
Consequently, the CKA is invariant to orthogonal transformations and isotropic scaling, and can be applied for the case where $\boldsymbol{h}^{\ell}$ and $\boldsymbol{h}^{\ell^{\prime}}$ have different dimensions.

### A simple method for measuring layer-wise representational similarity in transformers

In this paper, we specifically focus on transformer architectures that obey the following particular properties of features across layers: $(i)$ the features have the same dimension across layers since transformers are generally constructed by stacking identical blocks; $(ii)$ the features may have no or less rotation ambiguity due to the residual connection (1). Based on these observations, we propose to simply measure the cosine similarity of features $\boldsymbol{h}^{\ell}$ and $\boldsymbol{h}^{\ell^{\prime}}$ at layers $\ell$ and $\ell^{{}^{\prime}}$ as(^1^11The features in each layer are centered by reducing the global mean of all the samples.)

$$ $\operatorname{COS}=\langle\boldsymbol{h}^{\ell},\boldsymbol{h}^{\ell^{\prime}} \rangle/\|\boldsymbol{h}^{\ell}\|_{2}\|\boldsymbol{h}^{\ell^{\prime}}\|_{2}.$ $$

The above COsine Similarity (COS) measures the angle between feature vectors, providing a clear geometric interpretation of feature alignment and similarity at the layer level. Unlike CKA (2), COS is not invariant to all transformations except for isotropic scaling. Furthermore, COS is computed for each individual sample and does not rely on inter-example structures. In the experiments, we compute the average COS over all the training samples.

Figure: ((a))
Refer to caption: extracted/5681537/figures/Chapter2/cifar10_acc_cka_cos.jpg

To verify whether the proposed sample-wise COS is a good indicator of similarity structure within transformers, we train the DeiT-S model [] (a data-efficient vision transform) from scratch on both the CIFAR-10 and ImageNet datasets. The feature dimension is set to 384 for both tasks across all layers. In Figure 2(a, b), we compute CKA and average cosine similarity between the features in each layer and the last layer. Additionally, we plot average cosine similarities between all pairs of layers and display the results as a heatmap in Figure 2(c, d). Based on these results, we make several observations:

- •
COS reflects CKA in measuring layer-wise representation similarity We observe from Figure 2(a, b) that COS aligns with CKA and is sufficient to reflect the layer-wise representation similarity in transformer models. In other words, since CKA is invariant to orthogonal transformations while COS is not, there is little or no rotation difference among the features from different layers. This is attributed to the residual connections in (1), which create smoother transitions between layers and potentially lead to more stable feature representations throughout the network. In the appendix, we design additional experiments on multi-layer perceptrons (MLPs) with and without skip connections to verify the effect of skip connections in eliminating rotation ambiguity.
- •
Positive cosine layer-wise representation similarity.
For models trained on small datasets, we observe a ridge-to-plateau pattern in the heatmap plot in Figure 2(c): the initial layers undergo significant transformations, suggesting that lower layers rapidly refine the features to extract the most relevant information for classification tasks; in contrast, the higher layers exhibit a plateau in similarity scores, indicating that feature transformations stabilize and converge toward an optimal representation. This plateau also suggests redundancy in the higher layers, implying that removing these redundant layers could improve efficiency without significantly sacrificing performance. On the other hand, for models trained on large datasets, Figure 2(c) shows a consistent ridge pattern, characterized by a rapid decay in similarity between adjacent layers. This indicates a dynamic and continuous refinement process throughout the network. Nevertheless, for both Figure 2(c, d), we observe almost all nonnegative average cosine similarity between different layers, albeit the features are almost orthogonal when the layers are far apart.(^2^22There may be some rare samples with negative sample-wise cosine similarity between features from layers that are far apart; see additional figures with box plot in the Appendix.)
- •
Alignment between layer-wise cosine similarity and accuracy. Inspired by the similarity between features in shallow and deep layers, we apply the classifier to each hidden layer to get the layer-wise validation accuracy, which is plotted in Figure 2(a, b). We observe a high correlation between the layer-wise accuracy and the cosine similarity.

### Connection to neural collapse (NC)

We conclude this section by briefly introducing the neural collapse (NC) phenomenon [] and its connection to layer-wise representation similarity. We will exploit the observation of NC to develop methods for improving representation similarity in the next section. Roughly speaking, NC concerns the terminal phase of training deep networks and states that $(i)$ the last-layer features from the same class become nearly identical, $(ii)$ those from different classes become maximally linearly separable, and $(iii)$ the last-layer linear classifiers $\boldsymbol{W}$ align with the class-mean features. To achieve this, deep classifiers progressively compress within-class features while enhancing the discrimination of between-class features from shallow to deep layers [, , ]. The high correlation between the
layer-wise accuracy and the cosine similarity observed in Figure 2(a, b) is consistent with NC that the classifiers align with the class-mean features and the last-layer features from the same class become nearly identical. In addition, our results show that transformer models not only progressively compress within-class features, but also progressively align the features with the last-layer classifier from shallow to deep layers.

## 3 Aligned Training for Enhancing Layer-wise Representational Similarity: Application for Multi-Exit Models with a Single Classifier

In the previous section, we observed that representations across layers within transformer models are positively correlated, although this similarity diminishes as the layers become further apart. This layer-wise similarity can be captured by a simple sample-wise cosine similarity metric. This implies that the last-layer classifier can be directly applied after any hidden layers, enabling a multi-exit model that shares the same classifier. In this section, we propose an aligned training method to enhance this layer-wise feature similarity and hence the performance when served as mutli-exit models. To the best of our knowledge, our work is the first to show that one common classifier is sufficient for multi-exit models. A simple classifier can significantly reduce the number of parameters and the computational complexity for multi-exit models, particularly for tasks with a large number of classes and large feature dimensions. Examples include ImageNet, with 1000 classes, and LLMs, where the number of classes equals the vocabulary size, i.e., the number of all possible tokens—for instance, the Llama-2 [] model has a vocabulary of $32,000$ tokens while the GPT3 [] has $50,257$ tokens.

For input $\boldsymbol{x}$, recall that $\boldsymbol{h}^{\ell}$ denotes the $\ell$-th layer feature corresponding to a particular token on which predictions are based. Specifically, with $(\boldsymbol{W},\boldsymbol{b})$ denoting the linear classifier, both image classification and next token prediction are performed using $\boldsymbol{W}\boldsymbol{h}^{L}+\boldsymbol{b}$. Let $\boldsymbol{y}$ denote the corresponding label for $\boldsymbol{x}$. The standard training amounts to minimize the cross-entropy loss of form $\mathcal{L}_{\text{CE}}(\boldsymbol{W}\boldsymbol{h}_{L}+\boldsymbol{b},
\boldsymbol{y})$ over many paired training examples. To simplify the notation, we will present the training loss for a single sample
$\boldsymbol{x}$. However, this can be straightforwardly extended to all training samples by taking the average of the training losses over all the samples, i.e., the empirical risk.

The ability to capture the layer-wise similarity of representations for each sample enables us to develop efficient methods for enhancing this similarity during training. A first approach is to directly add the cosine similarity between $\boldsymbol{h}^{\ell}$ and $\boldsymbol{h}^{L}$ for all $\ell<L$ as a regularization term during the training process. However, as shown in the appendix (see Figure 13), this approach can only slightly improve layer-wise similarity and accuracy. We conjecture this is due to the imbalance between the cross-entropy loss and the cosine similarity. Instead, we will propose another approach inspired by the neural collapse phenomenon.

### Neural collapse inspired aligned training

Motivated by the self-duality between the class-mean features and the linear classifiers, as observed in the NC phenomenon, we propose a simple yet efficient method, named aligned training, to enhance the layer-wise similarity by jointly optimizing the following aligned loss that is the weighted average of the CE loss from all the layers

$$ $\mathcal{L}_{\text{aligned}}(\boldsymbol{x},\boldsymbol{y})=\sum_{\ell=1}^{L} \lambda_{\ell}\mathcal{L}_{\text{CE}}(\boldsymbol{W}\boldsymbol{h}^{\ell}+ \boldsymbol{b},\boldsymbol{y}),$ (3) $$

where $\lambda_{\ell}>0$ is the weight for the $\ell$-th layer. During the experiments, considering that shallow layers tend to have larger losses compared to deep layers, we set the weight to linearly increase as $\lambda_{\ell}=2\ell/(L(L+1))$. Roughly speaking, the aligned loss (3) introduces CE loss for intermediate layers and would encourage each layer features $\boldsymbol{h}^{\ell}$ to align with the common classifier $\boldsymbol{W}$—as implied by the NC phenomenon—hence improving the representation similarity across layers.

Figure: ((a))
Refer to caption: extracted/5681537/figures/Chapter3/cosine_similarity_with_last.png

### Improved layer-wise representation similarity and accuracy

Figure 3(a,c) display the layer-wise representation similarity by the proposed aligned training. We can observe that aligned training can significantly increase the pair-wise features from different layers by aligning all the features to the common classifier. Consequently, as shown in Figure 3(b), the layer-wise accuracies obtained by applying the last-layer classifier after each hidden layer are also dramatically improved compared with standard training.

Figure: ((a))
Refer to caption: extracted/5681537/figures/Chapter3/cifar10_layerwise_acc.jpg

### Determine minimal number of layers

While more difficult tasks generally require more layers, determining the exact number of layers for each task can be challenging. The aligned training method can help identify the minimal number of layers needed by unleashing the power of shallow layers to transform features faster towards classifier across layers and push the redundancy behind. As shown in Figure 4 with a DeiT-small model on CIFAR10, the transformer model obtained through the aligned training method achieves layer-wise accuracies that increase rapidly and then plateau across layers. One can identify the minimum number of layers by selecting the smallest layer that achieves nearly the highest accuracy or the targeted performance. Note that there is no need to retrain the model; one can simply use the selected layers along with the last-layer linear classifiers thanks to the aligned training approach. In contrast, Figure 4 also displays the layer-wise accuracies of three models with standard training and varied number of layers. The accuracy curves increase until the last layer without plateauing, even for the model with 12 layers. In this case, one would need to train multiple models of different sizes to identify the minimal number of layers required. It is also of interest to observe that the model by aligned training, if truncated to either 6 layers or 9 layers, archives slightly higher accuracy than the model of the same size trained by standard training. This advantage aligns with the common observation that training a larger model is relatively easier and is partly due to the fact that aligned training enables the features in shallow layers to mimic those in deeper layers. This resembles model distillation, albeit here the shallow features receive guidance from the deep ones. Further evidence is shown in Figure 4(b), where aligned training speeds up model convergence due to the immediate feedback provided to each layer, allowing for more effective parameter adjustments. Aligning features towards a common classifier also reduces internal covariate shift and helps optimize parameters across layers.

### Multi-exit model with a single classifier

Another important application of the proposed aligned training is to improve the inference efficiency of large models. In particular, the fast-increasing layer-wise accuracies imply that the model can exit at earlier layers. This suggests that when deploying the model on multiple devices with varying memory sizes and computational budget constraints, a single large model can be trained and then adapted to each device by selecting the appropriate number of sublayers from shallow to deep during inference. Even when the entire model can be fully deployed, it is still desirable to allow early exit during inference to save computation time, which is referred to as multi-exit models [, , ].

In previous work, multi-exit models use different classifiers for different layers, which can significantly increase the model size. This is especially true when the number of classes is large, as the dense linear classifiers contain a substantial number of parameters. To our knowledge, by exploiting the representation similarity within the transformer, our proposed multi-exit model is the first to use a single classifier for all the layers. In addition, when training multi-exit models, previous work [] often uses additional KL-divergence terms to guide the logits of shallow layers by those of deep layers. In contrast, by using a common classifier to align shallow representations with deep ones, our aligned training does not require KL-divergence or other such terms. For comparison, we adopt the multi-exit training with multiple classifiers [], denoted by “multi-exit/classifiers", and display the results in Figure 3. On one hand, we observe that the proposed aligned training with a shared classifeir achieves higher layer-wise representation similarity than multi-exit/classifiers. On the other hand, the aligned training exhibits on-par performance as multi-exit/classifiers in terms of layer-wise accuracy, which is remarkable as the former only uses a single classifier.

Figure: Figure 5: Number of samples exit at each layer during inference.
Refer to caption: extracted/5681537/figures/Chapter3/exit_counts.png

To further show the performance of the proposed multi-exit models with a single classifier, we allow exit at shallow layers if the confidence level (max of softmax logits) exceeds a set threshold for each sample. On ImageNet dataset, Figure 5 displays the number of samples that exit at each layer. We observe that most samples exit at the last layer for standard training, while most exit at early layers for aligned training.
We then calculate the classification accuracy along with the ratio of speed improvement measured by $\frac{\sum_{i=1}^{L}L\times m^{i}}{\sum_{i=1}^{L}i\times m^{i}}$
where $m^{i}$ is the number of samples that exit at the $i$-th layer of DeiT. The model trained with standard training achieves 80.28% accuracy, while the model trained with aligned training achieves 77.96% accuracy with a $1.36\times$ speedup, which is comparable to those trained by multi-exit/classifiers with 78.32 % accuracy and $1.42\times$ speedup.

### Effects on transferability

It is often claimed that shallow layers learn universal patterns while deep layers fit to class labels. Questions arise about whether the proposed aligned training approach is that aligning shallow layer features with deep layer features could cause the shallow layers to lose their transferability. To resolve this question, we conduct two sets of experiments:

- •
Distribution shift: we first train a DeiT on CIFAR10 with standard training and align training, and then evaluate the layer-wise accuracy on CIFAR10.2 [],
- •
Transfer to different tasks: we first train a DeiT on ImageNet with standard training and align training, and then evaluate the layer-wise accuracy on CIFAR10 by only fine-tune a linear classifier, with the feature mapping fixed.

Figure: ((a))
Refer to caption: extracted/5681537/figures/Chapter3/cifar10_to_cifar102.png

The results are plotted in Figure 6. We observe that for both cases, the distribution shift and transferring to different tasks, layer-wise accuracy curves resemble those on the pre-trained datasets shown in Figure 4 and Figure 3, demonstrating that aligned training not only improves layer-wise accuracy for the pre-trained datasets but also for the downstream datasets. In other words, the aligned training methods maintain transferability, ensuring that the trained model can be effectively transferred.

## 4 Applications on Language Models

All the previous experiments mainly focus on ViT for vision tasks. In this section, we will present additional experiments to demonstrate the performance of the aligned training for fine-tuning LLMs for NLP tasks. Specifically, we empirically evaluate the approach on text classification by fine-tuning the pretrained BERT models and generation tasks by fine-tuning the GTP2 model. For comparison, we also independently finetune the baseline models for both tasks using standard training.

Figure: ((a))
Refer to caption: extracted/5681537/figures/Chapter4/SST2.png

### AlignedBERT: text classification tasks

We first study the text classification problem using the BERT model, which is similar to ViT for image classification as BERT also employs the [CLS] token for classification. We take a pretrained 12-layer BERT-Base model, extract the feature tied to the [CLS] token from each layer, and apply the same classification head to derive logits from each layer. Subsequently, we employ the aligned loss for fine-tuning to obtain the so-called AlignedBERT. We test AlignedBERT on the General Language Understanding Evaluation (GLUE) benchmark, which encompasses nine tasks that gauge understanding of natural language. This includes single-sentence tasks such as CoLA and SST-2, similarity and paraphrasing tasks like MRPC, STS-B, and QQP, as well as natural language inference tasks - MNLI, QNLI, RTE and WNLI. The accuracy or F-1 score per layer is depicted in Figure 7. AlignedBERT demonstrates better performance than the standard baseline for layer-wise accuracy. This indicates that most layers are redundant and that using only the first few layers of AlignedBERT can achieve good text classification performance.

Figure: ((a))
Refer to caption: extracted/5681537/figures/Chapter4/gpt_layerwise_acc.png

### AlignedGPT: text generation tasks

We then study open-ended text generation due to its widespread applicability in various areas. In formal terms, given a human-written prefix or context $\boldsymbol{x}$, the task involves decoding a continuation from the language model using the auto-regressive approach that predicts one token each time. The prediction of the next token is the same to a classification problem: given current tokens $\boldsymbol{x}$ as input, the transformer processes them as in (1), and then makes the prediction based on the feature $\boldsymbol{h}^{L}$ of the last token. The transformer is also trained with CE loss where the expected next token is the label and the last-layer linear classifier (generation head) $\boldsymbol{W}$ represents the embeddings for all the possible tokens. To improve representation similarity across layers so that features from early layers can also predict the next token, we use aligned training to finetune the auto-regressive model as in (3) that appends CE loss across shallow layers.

For both the standard model and the model fine-tuned with aligned training, we can generate text from the intermediate layers by extracting hidden states from these layers and passing them to the last-layer classifier to get the next token logits. These logits are then used by certain decoding methods to generate the new token. Following [, ], we evaluate the generated text from two perspectives: (1) language modeling quality, which assesses the intrinsic quality of the model and is measured by prediction accuracy and perplexity, and (2) generation quality, which measures the quality of the text produced by the model using coherence and diversity. Coherence is a measurement of relevance between prefix text and generated text, while diversity considers the recurrence of generation at varying n-gram levels. See the Appendix for the details.

In this experiment, we fine-tune GPT-2 on the Wikitext-103 dataset and show the results in Figure 8. In terms of model quality, AlignedGPT outperforms the standard GPT-2 in prediction accuracy and exhibits lower perplexity across intermediate layers, excluding the last layer where the two models achieve comparable performance. Regarding the quality of text generated from intermediate layers, AlignedGPT also excels in maintaining higher coherence and diversity. This suggests that we can utilize the shallower layers for text generation to improve inference efficiency without significantly reducing the quality of the generated text.

## 5 Conclusion

In this paper, we have shown that a simple sample-wise cosine similarity metric is capable of capturing layer-wise representation similarity of transformer models and aligns with complicated ones such as the CKA. We then propose an aligned training approach to enhance the similarity between internal representations, with trained models achieving much higher layer-wise accuracies than those under standard training. Remarkably, when served as multi-exit models with a common classifier, which to our knowledge is the first of its kind, they maintain the early exit capability and achieve performance on par with models that use multiple classifiers.
Experiments on both vision and NLP tasks demonstrate the performance of the proposed aligned training.

## Acknowledgement

We acknowledge support from NSF grants CCF-2240708 and IIS-2312840. We are grateful to Chong You (Google Research) for many valuable discussions and for helpful comments on the manuscript.

## Appendix A Box Plots of Sample-wise Cosine Similarity

Figure 2(c, d) show that the average cosine similarities are almost nonnegative between different layers, albeit the features are almost orthogonal when the layers are far apart. Here we plot further information beyond the average. Here, we show the distributions of the cosine similarity between each layer and the last layer for all the data points. In particular, Figure 9 displays the box plot in terms of the minimum, maximum, sample median, and the first and third quartiles as well as any outliers for the cosine similarity.
We observe that the majority of the cosine similarities are nonnegative, but also that some rare samples exhibit negative sample-wise cosine similarity between features from layers that are far apart, such as between the first layer and the last layer.

Figure: ((a))
Refer to caption: extracted/5681537/figures/Appendix/box_cifar10_cos.png

## Appendix B Residual Connections Eliminate Rotation Ambiguity

Figure: ((a))
Refer to caption: extracted/5681537/figures/Chapter2/box_cos_sim_with_adjacent_layer.png

Section 2 demonstrates a consistent trend between COS and CKA. Additionally, recalling that $\boldsymbol{h}^{\ell}$ denotes the $\ell$-th layer feature corresponding for each input, 10(a) shows the average cosine similarity of features from adjacent layers, i.e., $\operatorname{COS}(\boldsymbol{h}^{\ell-1},\boldsymbol{h}^{\ell})$. We observe that each layer exhibits high similarity with its adjacent layers. All these findings suggest the existence of no rotation ambiguity when measuring the similarity between different layers. In this section, we further examine the role of skip connections in eliminating rotation ambiguity.

As illustrated in (1), most transformer architectures include skip connections in both the self-attention block and the MLP block, giving the following update of features in each layer:

$$ $\displaystyle\boldsymbol{h}^{\ell+1}$ $\displaystyle=\underbrace{\text{MLP}(\text{LN}(\text{MSA}(\text{LN}( \boldsymbol{h}^{\ell})+\boldsymbol{h}^{\ell}))+\text{MSA}(\text{LN}( \boldsymbol{h}^{\ell}))}_{f(\boldsymbol{h}^{\ell})}+\boldsymbol{h}^{\ell},$ $$

where $f(\boldsymbol{h}^{\ell})$ represents the transformation of $\boldsymbol{h}^{\ell}$ from the long branch. To investigate the effect of residual connections, we calculate the norm ratio $\|\boldsymbol{h}^{\ell}\|/\|f(\boldsymbol{h}^{\ell})\|$ as well as the cosine angle between $\boldsymbol{h}^{\ell}$ and $f(\boldsymbol{h}^{\ell})$, and display the results in Figure 10(b,c). We observe that $(i)$ the residual component $f(\boldsymbol{h}^{\ell})$ is almost orthogonal to the input $\boldsymbol{h}^{\ell}$ of each block, and $(ii)$ the norm of residual component $f(\boldsymbol{h}^{\ell})$ is much smaller than the input $\boldsymbol{h}^{\ell}$, which together explain the large similarity of the features from adjacent layers.

Figure: ((a))
Refer to caption: extracted/5681537/figures/Chapter2/MLP_acc_cos_cka.jpg

To provide further evidence that residual connections resolve the rotation ambiguity, we conduct experiments to compare the performance with and without the residual connection in each layer. Since we find the ViT is very hard to train when the residual connection is removed, instead we perform the experiments with a standard MLP model. In Figure 11, we show the results of layer-wise similarities measured by COS and CKA as well as layer-wise accuracy for both the standard MLP without a residual connection and the modified MLP that includes residual connections between adjacent layers. For the MLP model without residual connections, as shown in Figure 11(a), the cosine similarity is not consistent with the CKA value.
In contrast, for the MLP model with residual connections, as depicted in Figure 11(b), the CKA value aligns with the cosine similarity and layerwise accuracy, indicating that residual connections effectively eliminate the rotation ambiguity of features. This observation is consistent with those observed with the transformer models.

## Appendix C Setup for Aligned Training

Figure: Figure 12: Aligned training of transformer using joint CE loss of all layer features with common classifier and elastic inference for different memory constrains—once the model is trained using the aligned method, it can fit all devices. Here features from darker layers indicate better performance.
Refer to caption: extracted/5681537/figures/show.png

### Setup for Aligned Training.

Figure 12 illustrates aligned training $\mathcal{L}_{\text{aligned}}(\boldsymbol{x},\boldsymbol{y})=\sum_{\ell=1}^{L}
\lambda_{\ell}\mathcal{L}_{\text{CE}}(\boldsymbol{W}\boldsymbol{h}^{\ell}+
\boldsymbol{b},\boldsymbol{y})$ and multi-exit model with a single classifier, which can be adapted to different devices with varying memory sizes and computational budget constraints by selecting the appropriate number of sublayers from shallow to deep during inference. We observe that directly minimizing the weighted average of the CE losses from all the layers causes a performance drop for the entire network, a phenomenon also observed in multi-exit training with multiple classifiers. In the experiments, our aligned training method adopts an alternating training approach [] that alternatively minimizes the weighted average of the CE losses from all the layers $\mathcal{L}_{\text{aligned}}(\boldsymbol{x},\boldsymbol{y})=\sum_{\ell=1}^{L}
\lambda_{\ell}\mathcal{L}_{\text{CE}}(\boldsymbol{W}\boldsymbol{h}^{\ell}+
\boldsymbol{b},\boldsymbol{y})$ and the standard CE loss from the last layer $\mathcal{L}_{\text{CE}}(\boldsymbol{W}\boldsymbol{h}^{L}+\boldsymbol{b},
\boldsymbol{y})$. But we note that our aligned training method no longer requires the KL-divergence term that is commonly used in mutli-exit/classifeirs training [] to guide the shallower layers. When using a common classifier, our aligned training method enables shallow layers to mimic or align their feature representations with those of the deep layers by aligning with the common classifier. As such, the deep layers, with their advanced feature representations, act as the teachers, while the shallow layers, in their quest to improve their feature extraction capabilities, assume the role of students. Therefore, the KL-divergence term is no longer necessary.

Figure: ((a))
Refer to caption: extracted/5681537/figures/Chapter3/in1k_cosine_similarity.png

### Alternative Approach for Enhancing Layer-wise Representation Similarity.

Besides using the weighted average of the CE losses from all the layers to enhance similarity, another approach is to directly incorporate the following cosine similarity as a regularization term in the loss function:

$$ $\mathcal{L}_{\text{sim}}(\{\boldsymbol{h}^{\ell}\})=\sum_{l=1}^{L}\lambda_{ \ell}(1-\cos(\boldsymbol{h}^{\ell},\boldsymbol{h}^{L})),$ $$

where $\lambda_{\ell}>0$ is an appropriate weight for the $\ell$-th layer, resulting in the following regularized training loss

$$ $\mathcal{L}_{\text{CE-reg}}(\boldsymbol{x},\boldsymbol{y})=\mathcal{L}_{\text{ CE}}(\boldsymbol{W}\boldsymbol{h}^{L},\boldsymbol{y})+\beta\mathcal{L}_{\text{ sim}}(\{\boldsymbol{h}^{\ell}\})$ $$

where $\beta>0$ is the regularization coefficient. Unfortunately, as shown in Figure 13, we observe the regularization term contributes minimally to the improvement of cosine similarity and layer-wise accuracy, compared to aligned training methods.

### Setup in AlignGPT.

Below we present the detailed setup for fine-tuning GPT-2 on the Wikitext-103 dataset, with results shown in Figure 8.

- •
Model and Baselines We fine-tune GPT-2 on the Wikitext-103 dataset with the proposed objective $\mathcal{L}{\text{aligned}}$ for 40k training steps and generate text continuation using nucleus sampling  [] with $p=0.95$ decoding methods. For the standard baseline model, we fine-tune the model with the CE loss $\mathcal{L}{\text{MLE}}$. The model is fine-tuned using a single 24G RTX A5000 GPU for 70 hours.
- •
Evaluations Following [], we evaluate the model from two perspectives: (1) language modeling quality, assessing the inherent quality of the model, and (2) generation quality, measuring the quality of the text the model produces. In assessing language modeling quality, we calculate the prediction accuracy and perplexity of each layer. When evaluating generation quality, we measure the similarity between the prompt text and generated text using coherence. We employ generation repetition to gauge the diversity of the generated text. The metrics are defined as follows:
–
Prediction Accuracy is computed on the Wikitext-103 test set as
$\textbf{Acc}=\frac{1}{nD}\sum_{i=1}^{D}\sum_{i=1}^{n}\mathbbm{1}[\operatorname
*{\text{arg~{}max}}p_{\theta}(x|\boldsymbol{x}_{<i})=x_{i}]$
(4)
where the $D$ is the number of samples in the test dataset.
–
Perplexity is computed as the exponential of the text loss on the test set of Wikitext-103.
–
Coherence measures the relevance between the prefix text and the generated text. We apply the advanced sentence embedding method, SimCSE [], to measure the semantic coherence or consistency between the prefix and the generated text. The coherence score is defined as follows,
$\textbf{Coherence}=\boldsymbol{h}_{\boldsymbol{x}}^{T}\boldsymbol{h}_{\hat{
\boldsymbol{x}}}/\|\boldsymbol{h}_{\boldsymbol{x}}\|\|\boldsymbol{h}_{\hat{
\boldsymbol{x}}}\|$
(5)
where $\boldsymbol{x}$ is the prefix text and $\hat{\boldsymbol{x}}$ is the generated text and $\boldsymbol{h}_{\boldsymbol{x}}=\text{SimCSE}(\boldsymbol{x})$ and $\boldsymbol{h}_{\hat{\boldsymbol{x}}}=\text{SimCSE}(\hat{\boldsymbol{x}})$. Higher coherence means more correlation to the given prompt.
–
Diversity measures the occurrence of generation at different n-gram levels:
$\textbf{Diversity}=\prod_{n=2}^{4}\frac{|\text{unique n-grams}(\hat{
\boldsymbol{x}})|}{\text{|total n-grams}(\hat{\boldsymbol{x}})|}$
(6)
A higher diversity score suggests fewer repeated words in the generated text.

## Peer Reviews

confidence: 3
contribution: 2
initial_rating: 3
presentation: 3
questions: Please refer to the weaknesses part.
soundness: 2
strengths: - The manuscript is logically organized, including the observations and its applications.
- Both empirical and theoretical justifications are provided.
- The study covers both the vision and language domains.
summary: This work studies the feature similarity of neural networks and reveals that: (I) simple-wise cosine similarity can capture representation similarity; (ii) saturation events related with feature similarity and based on this observations, this work proposed a aligned training approach to enhance the representation thus benefit the performance and also the multi-exit inference approach.
weaknesses: - Line 342 “To the best of our knowledge, our work is the first to show that one common classifier is sufficient for multi-exit models.” This is not true, a lot of early exiting methods can do with a single classifier heads [1-3].
- Line 240: “Progressively increasing layer-wise representation similarity”, thus observations might be different in other domain[2], is there any insights why autoregressive models seems not have progressively increasing layer-wise representation similarity?
- Missing previous literature[4] which also studies layer-wise cosine similarity, yet in the language domain.

[1] https://proceedings.neurips.cc/paper_files/paper/2022/file/6fac9e316a4ae75ea244ddcef1982c71-Paper-Conference.pdf

[2] https://arxiv.org/pdf/2404.03865

[3] https://arxiv.org/pdf/2403.03853

[4] https://arxiv.org/pdf/2202.08625

---

confidence: 3
contribution: 3
initial_rating: 6
presentation: 3
questions: Based on the weaknesses, I have some questions.

1. Is enhancing similarity beneficial for all tasks besides the simple classification task?

2. When enlarging the data/model size, will the method/analyses still works?
soundness: 3
strengths: In general, the proposed paper is well-written, the author provides detailed experiments, extensive theoretical analysis to analysis the feature pattern in Transformers. Based on these analyses, the author proposes a aligned training method for enhancing shallow layer performance. The proposed method achieves performance gain and speed boost on CV and NLP tasks.
summary: This paper focuses on understanding the behavior of deep neural networks, particularly transformer models, by examining the similarity of internal representations across hidden layers. The authors introduce a sample-wise cosine similarity metric that aligns with more complex statistical methods and reveals increasing representation similarity as layers get closer. They provide a theoretical justification for this phenomenon under the geodesic curve assumption and demonstrate that enhanced representation similarity leads to increased predicted probability and earlier saturation events in model predictions. The paper proposes an aligned training method to improve shallow layer effectiveness, resulting in more early saturation events and higher layer-wise accuracies. Finally, the authors show that their approach enables multi-exit models with a single classifier, reducing parameter count and computational complexity while maintaining performance.
weaknesses: In general, I think the proposed paper is well formulated and written. However, I still have some concerns about the paper:

1. I don't think it is useful for enhancing similarity between all Transformer outputs (representations), it may help in simple tasks like image classification and sentence classification. But for complex tasks (like object detection/semantic segmentations), we may not want all representations to be similar. I think similar tasks may exist in NLP tasks (like parsing), Then the author should talk about the limitations or give more experiments to verify the effectiveness of the proposed method.

2. In the paper, the author performs experiments on small datasets and small models, like DeiT trained on CIFAR10 and ImageNet. Also Bert/GPT2 on small NLP tasks. If the data increases, like a pre-trained CLIP/OpenCLIP on large datasets, will the findings/analyses be the same? Moreover, if the model becomes larger (like a LLM like Llama3), will the findings/analyses be the same? Does the saturation events still occur in those models? I'm curious about that.

---

confidence: 2
contribution: 3
initial_rating: 6
presentation: 3
questions: I have a few questions about this submission.
1. According to Figure 6, does the proposed aligned training strategy decrease the performance more clearly in the last layers in large models? Please discuss the performance trade-offs between shallow and deep layers across different model sizes.
2. With the common classifier, is there still a neural collapse phenomenon in the model? Is there any difference of this phenomenon across different layers? I'd like to see some discussions about this.
soundness: 3
strengths: 1. By analyzing the similarity of representations among different layers, the paper demonstrates the possibility of early saturation events and shared classifier among different layers.
2. They further presents a training strategy to improve effectiveness of shallow layers, such that they can enjoy more early saturation events, minimal depth, and so on
3. Some analysis in this paper is insightful, e.g., the shadow layer is able to achieve approaching performance with the depth layer. This might inspire more efficient large model inference.
4. The experiments are comprehensive.
summary: This paper focuses on the analysis of layer-wise representations of Transformers. They demonstrates a series of beneficial observations, e.g., representations across layers are positively correlated. Meanwhile, they find the model's top prediction remains unchanged across subsequent layers. Following the observation, they further propose an aligned training strategy to improve the effectiveness of shallow layer, which is able to provide more early saturation events, minimal depth needed for the given task, multi-exit models.
weaknesses: 1. a small weakness is that the previous approaches have observed this phenomenon that representations in the early layers can also achieve reasonable classifiers, though I think this is a tiny issue.
Please refer to the Questions.

---

confidence: 5
contribution: 3
initial_rating: 5
presentation: 3
questions: 1. Why use linearly increasing weights for aligned losses? Experiments for different choices on weights are preferred.
soundness: 3
strengths: 1. The deduction and experiments in the paper are relatively solid. The authors have made efforts to investigate the similarity of representations across different layers in transformers. 

2. The paper is well-written and easy to follow.
summary: This paper studied the similarity of representations between the hidden layers of individual transformers and found that a simple cosine similarity metric can be used for similarity evaluation. Experimental results revealed that representations across layers are positively correlated and the authors introduce a multi-exit mechanism. The innovation lies in using the same classifier for different layers.
weaknesses: Using the same classifier for multi-exit is quite straightforward and its technical contribution seems limited. The experimental results seem not very promising compared with previous multi-exit methods. The authors may need to further enhance the novelty or provide more convincing evidence of the superiority of their approach compared with multi-exit/classifier to make the paper more acceptable.

Meta-review: This paper examines the similarity of internal representations across hidden layers for transformer models. The authors introduce a sample-wise cosine similarity metric and show that enhanced representation similarity leads to increased predicted probability and earlier saturation event, enabling multi-exit models with a single classifier.

However, according to the reviewers, the method might face weaknesses such as generalization to other tasks besides those presented in the paper, and the observation that early exist can perform reasonably well has been reported in the past. 

Based on the thorough discussions and experimentations of the paper, and the statistical explanation of the observed phenomena, I would therefore suggest accepting the paper.

Decision: Accept (Poster)