Manuscript Offprint
arXiv:2610.13261Data-Adaptive Mahalanobis Metric Learning for Cross-Head Attention in Transformers
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
In this paper, we propose Data-Adaptive Mahalanobis Cross-Head Attention (DAM-CHA), a simple and effective attention mechanism that generalizes Multi-Head Attention (MHA) through the lens of metric learning. Standard MHA implicitly learns a static, head-wise Euclidean similarity corresponding to the diagonal blocks of a unified cross-head metric matrix, discarding all off-diagonal interactions across heads. DAMCHA addresses this limitation via two key innovations. First, it learns the full cross-head metric matrix, inducing a Mahalanobis-like similarity that explicitly captures inter-head interactions beyond the restricted block-diagonal structure of MHA. Second, it parameterizes the metric matrix as an input-dependent function, enabling the attention geometry to dynamically adapt to the intrinsic manifold structure of the data rather than remaining fixed after training. We further introduce principled regularization strategies, most notably stack-wise parameter sharing, to ensure computational efficiency and stable optimization. DAMCHA serves as a drop-in replacement for MHA and its variants in various Transformer architectures, delivering superior expressive power and learning performance with comparable or reduced computational overhead. Extensive experiments demonstrate that DAMCHA-based Transformers consistently outperform competing baselines across a range of benchmark tasks. Code is available at https://github.com/erwinmsmith/DAMCHA.
1 Introduction
MHA is a core block of Transformer architecture [1, 2, 3]. MHA essentially learns a set of similarity matrices induced by a bilinear form (usually denoted as ) through a query-key mechanism [4, 5, 6]. These learned head-wise metrics are used to compute attention scores, which capture token matching intensities across disparate representation subspaces [2, 7, 8]. This formulation naturally aligns MHA with metric learning, where discriminative similarity structures are learned to support downstream tasks.[9, 10, 11, 12, 13].
Despite its extensive successes in diverse domains [14, 15, 16], when examined through this lens, standard MHA exhibits several inherent structural deficiencies that limit its expressive power. First, it
Corresponding author.
40th Conference on Neural Information Processing Systems (NeurIPS 2026).
assumes conditional independence between heads for a given input, where similarities are defined solely within each head and merely concatenated at the output. This ignores the cross-head synergies and higher-order interactions corresponding to for , making it difficult to represent coupled geometries between complex feature subspaces [17, 18, 19]. Second, the similarity metrics remain static post-training, which implies that, during inference, the attention cannot adapt to the input data, failing to match the non-linear and locally anisotropic manifold structures prevalent in real-world data. In addition, because relies on a factorized formulation, its rank is inherently capped by the projection dimension, introducing a well-known low-rank bottleneck that limits representation capacity [20, 21, 22]. These issues are especially problematic in tasks where the geometry of the data distribution is critical [23, 24].
In this paper, we propose a paradigm shift: rather than viewing the attention as a collection of independent, dot-product, head-wise matrices, it should be understood as a single, learnable Mahalanobis-like metric defined over the joint head space (Here, the term Mahalanobis-like is used to emphasize that our formulation can fully exploit off-diagonal blocks; we do not require the resulting Mahalanobis-like metric matrix to be positive definite). In contrast, standard MHA corresponds to a restrictive block-diagonal constraint that discards all off-diagonal couplings, thereby enforcing an effectively Euclidean similarity measure. From a learning perspective, MHA learns only a global, input-independent similarity matrix that approximates an average attention geometry across the dataset. Guided by this high-level interpretation, we propose a novel attention mechanism, termed DAMCHA. DAMCHA introduces two primary innovations. Structural Expansion: It eliminates structural independence by explicitly learning a full cross-head metric. While its diagonal blocks recover conventional within-head similarities, the off-diagonal blocks encode how different heads should cooperate, compensate, or modulate one another, expanding attention from an additive mixture of isolated similarities to a genuine Mahalanobis-like metric. Dynamic Adaptivity: Unlike MHA which keeps underlying parameters static, DAMCHA parameterizes the similarity matrix by a learnable function of the input. This allows the model to dynamically select appropriate geometries for different contexts, aligning the attention operator with the local structure of the data manifold. Several prior works have sought to improve upon MHA through head interaction or geometric enrichment, including THA [25], DCMHA [19], ColMHA [26], MoA [27], and MMA [28]. However, none of these approaches is grounded in metric learning, and none jointly addresses cross-head interaction and input-adaptive metric learning within a unified framework.
Practically, DAMCHA yields benefits beyond expressiveness: (i) improved modeling of complex dependencies spanning multiple semantic factors (e.g., content–position or syntax–semantics); (ii) enhanced adaptability under distributional shifts or heterogeneous inputs, as the attention geometry reconfigures itself to match the current context; (iii) by directly learning the similarity matrices s through a functional mapping rather than the conventional linear query-key projections, DAMCHA naturally bypasses the low-rank bottleneck. We further introduce principled regularization strategies, most notably stack-wise parameter sharing, to control model complexity. Since the attention matrices in DAMCHA are generated by a compact metric learner, the overall parameter count remains comparable to standard MHA despite the expanded metric structure. This design ensures that the gains in expressiveness come at no significant cost in computational overhead or memory footprint.
Experimental results show that DAMCHA outperforms Transformers across a variety of architectures (e.g. GPT-2) and scales. In language modeling, DAMCHA is particularly superior. Notably, DAMCHA yields improvements in token-level pretraining; these gains are even stronger on mixed datasets, which are inherently cross-view. We further validate DAMCHA on autoregressive, decoder-only Transformers as well as Vision Transformers in generative and discriminative tasks. We provide extensive simulation experiments and ablation studies to elucidate the mechanisms of DAMCHA.
From a metric learning perspective, attention can be interpreted as a parameterized similarity metric [6], and existing metric-aware designs focus on domain-specific settings [33, 34, 35, 36], neglecting multi-head structural features. There is currently no unified framework that integrates Mahalanobis metric learning with multi-head attention to jointly model both intra- and cross-head similarities, leaving open the question of whether similarity metric should adapt dynamically to the input or remain fixed after training [23, 37].
3 DAMCHA
3.1 Cross-Head Metric Matrix as a Conceptual Formulation
Let denote an input sequence of length , where , is the number of attention heads, and is the hidden dimension of each head. In standard multi-head attention (MHA), the -th head computes query and key representations as and , where . The corresponding pre-softmax score matrix is
Thus, from a metric-learning perspective, each head learns an independent bilinear similarity metric . Equivalently, standard MHA can be interpreted as a block-diagonal metric structure over the joint head space: . This block-diagonal structure implicitly assumes that the similarity geometry of each head is formed independently, without explicitly modeling metric-level interactions between different heads. To describe possible interactions beyond this restriction, we introduce the Cross-Head Metric Matrix (CHM):
where each block represents a potential metric-level interaction between the query subspace associated with head i and the key subspace associated with head j. When all off-diagonal blocks vanish, CHM reduces to the block-diagonal metric structure of standard MHA. When off-diagonal blocks are allowed, attention is no longer restricted to independent head-wise similarity measurements.
3.2 Adaptive Learning of CHM
Let denote the input token, and let each metric block satisfy . In MHA, all s are fixed after training, which implies that the same projection matrices are applied to all inputs in inference process. Although attention score vary with the input contents, the underlying metric itself is input-independent. In other words, MHA learns a static metric that is globally shared across all contexts. This static design may be suboptimal in practice. For instance, the relevance between two features may be strong in one context but weak in another [19, 38, 39, 40], yet a fixed metric cannot adapt its attention geometry accordingly.
To increase the expressiveness of the attention mechanism, we parameterize CHM as an input-dependent function. Concretely, a learnable forward network (e.g., an MLP or a hyper-network) is introduced to map X to an adaptive CHM, which follows
Under this formulation, each cross-head metric block is no longer a matrix with constant parameter, but is dynamically generated conditioned on the input X. Further discussions on the advantages of our method are provided in Appendix A.
3.3 Attention Mechanism based on CHM
We propose DAMCHA, a novel attention mechanism built upon CHM. We assume that has been generated by conditioned on the input sequence. DAMCHA consists of attention heads. For a given input , we first define the row-summed head metric for the -th head as
X is first linearly transformed to match the required dimensionality, Then, using , DAMCHA computes the score matrix for the i-th head via a generalized quadratic form:
where , and is set equal to the per-head dimension , consistent with the scaling in conventional MHA. Then, the attention matrix is obtained by applying a softmax operation:
For each head , we compute value representations as with projection . The output of the -th head is given by
where denotes the attention weight and is the corresponding value representation. The outputs from all heads are concatenated to form a joint output denoted as , given by
Then, is mapped back to the original feature dimension, yielding final output with projection .
The RowSum operation preserves cross-head coupling information while offering two additional advantages. First, whereas each head metric in standard MHA is rank-limited by the projection dimension, summing cross-head blocks elevates the effective rank upper bound, alleviating the low-rank bottleneck. Second, by compressing the full cross-head metric into a single effective matrix per head, RowSum preserves the standard multi-head output structure, allowing DAMCHA to serve as a natural drop-in replacement for MHA with negligible additional overhead. The workflows of DAMCHA and

Figure 1: The workflows of DAMCHA and MHA.
MHA are presented and compared in Figure 1. The data flow of DAMCHA is in Appendix B.
3.4 Stack-Wise Sharing Mechanism
In practical applications, attention modules are typically embedded within network blocks that must be stacked to build depth. Learning separate mappings (each outputting a different metric matrix for a different block) is not only computationally expensive, but also prone to severe overfitting. To address this issue, we share the parameters of across all stacked network blocks. That is, all layers employ the same feedforward network to generate the adaptive CHMs. The stack-wise parameter sharing strategy of DAMCHA is further illustrated using a basic decoder-only Transformer architecture, as shown in Figure 2.
(a)
(b)
(c)

Figure 2: A basic DAMCHA-based decoder-only Transformer architecture with stack-wise sharing.
This stack-wise sharing yields multiple benefits. First, it substantially reduces the total number of parameters, especially when stacking many layers, thereby mitigating overfitting. Second, it introduces an additional form of regularization by constraining all layers to reuse a consistent family of metric transformations. This prevents excessive divergence of attention geometries across layers and avoids conflicts between layer-specific metric adaptations. Empirically, we observe that this shared design leads to more stable training and improved performance in deep architectures.
It is noted that, in DAMCHA, no explicit structural constraints or prior assumptions are imposed on any of . This is in sharp contrast to MHA, where the similarity matrices associated with individual heads, i.e., , are inherently low-rank due to their dot-product formulation. By allowing all s to be freely learned without rank restrictions, DAMCHA effectively alleviates the low-rank bottleneck inherent in conventional attention mechanisms, further enhancing the expressive capacity of the model.
4 Theoretical View
We provide two theoretical results to justify DAMCHA, with proofs deferred to Appendix C. First, under mild expressivity assumptions on the metric generator, we prove that DAMCHA strictly generalizes standard MHA at the level of pre-softmax attention scores. This shows that DAMCHA is not merely a heuristic modification of MHA, but a strict functional extension. Second, we analyze DAMCHA from a metric-learning risk perspective. In heterogeneous data, different contexts may require different optimal similarity metrics. A static MHA metric must approximate all local geometries using a single global low-rank metric. In contrast, DAMCHA can condition its cross-head metric matrix on the input and select context-specific metrics. Under standard curvature and identifiability assumptions, the optimal risk of DAMCHA is no larger than that of MHA, with strict improvement whenever no single static low-rank metric can match all context-specific optimal metrics. For a detailed complexity analysis, see Appendix D.
5 Experiments
5.1 Decoder-Only Transformers with DAMCHA
Experimental Setting. We evaluate DAMCHA on both image and text generation tasks using decoder-only Transformers. For image generation, we train autoregressive models on CIFAR-10 and CIFAR-100, where images are flattened into sequences of tokens with 8-bit pixel values. For text generation, we use WMT14 [41] English-German translation and CommonGen [42] commonsense generation datasets. All models have 10 decoders, 8 attention heads, model dimension 512, and head dimension 64. Models are trained for 50 epochs with batch size 128, learning rate , and Adam optimizer. We evaluate the performance using mean square error (MSE) and
Fréchet Inception Distance (FID) for images, and Negative Log-Likelihood (NLL) and BARTScore for text. To assess performance on high-quality samples, we additionally report metrics on the top-50 samples ranked by their generation likelihood. For DAMCHA, the metric generator is implemented as a 9-layer MLP, following the capacity ablation in Section 5.3.
Table 1 compares DAMCHA with MHA and several recent baselines, THA [25], DCMHA [19], ColMHA [26], MoA [27], and MMA [28]. DAMCHA achieves the best quality across both tasks.
Image Generation Performance. On CIFAR-10, DAMCHA obtains the lowest MSE mean (0.1210) and FID mean (331.8906), and substantially improves FID@Top-50 from 91.4320 under MHA to 63.0295, corresponding to a relative reduction. Compared with the strongest non-DAMCHA baseline on FID@Top-50, i.e., MMA (84.9717), DAMCHA still achieves a relative reduction. On CIFAR-100, DAMCHA also achieves the best FID mean (314.5722) and FID@Top-50 (53.7560), outperforming both MHA and recent attention variants.
Table 1: Comparison with MHA and recent multi-head attention variants on generation tasks. For MSE/FID/NLL, lower is better (↓). For BARTScore, higher is better (↑).
| Image generation | MSE ↓ | FID ↓ | FID@Top-50 ↓ | Text generation | NLL ↓ | BARTScore ↑ | BARTScore@Top-50 ↑ | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Dataset | Method | mean | q25 | q75 | mean | q25 | q75 | Dataset | Method | mean | q25 | q75 | mean | q25 | q75 | ||
| CIFAR-10 | MHA | 0.1260 | 0.0750 | 0.1610 | 358.8570 | 293.0850 | 417.5810 | 91.4320 | WMT | MHA | 5.7730 | 5.1760 | 6.3750 | -8.4740 | -9.4590 | -7.3420 | -5.3090 |
| THA | 0.1357 | 0.0827 | 0.1726 | 366.7536 | 301.3989 | 421.4758 | 107.2156 | THA | 5.2368 | 4.5104 | 5.7082 | -6.7477 | -7.5275 | -5.8776 | -4.5788 | ||
| DCMHA | 0.1264 | 0.0758 | 0.1622 | 366.0802 | 297.8571 | 418.4777 | 105.1269 | DCMHA | 5.2461 | 4.5396 | 5.7308 | -6.8371 | -7.5254 | -6.0639 | -4.8286 | ||
| ColMHA | 0.1276 | 0.0752 | 0.1630 | 365.9343 | 298.6780 | 416.1373 | 120.1717 | ColMHA | 5.2432 | 4.5387 | 5.7324 | -6.1477 | -6.7462 | -5.4902 | -4.3363 | ||
| MMA | 0.1292 | 0.0771 | 0.1604 | 359.6663 | 267.3268 | 422.7725 | 84.9717 | MMA | 5.0301 | 4.5096 | 5.6847 | -8.3875 | -9.3292 | -7.3488 | -5.7903 | ||
| MoA | 0.1576 | 0.0988 | 0.2036 | 368.4184 | 297.8040 | 416.2914 | 98.5777 | MoA | 5.2703 | 4.5695 | 5.7369 | -6.9642 | -7.6396 | -6.2873 | -5.0395 | ||
| DAMCHA | 0.1210 | 0.0730 | 0.1547 | 331.8906 | 297.1379 | 411.8182 | 63.0295 | DAMCHA | 5.1907 | 4.4945 | 5.6793 | -5.4451 | -6.0953 | -5.1735 | -4.1410 | ||
| CIFAR-100 | MHA | 0.1250 | 0.0737 | 0.1600 | 358.1270 | 293.7460 | 418.5330 | 59.6860 | CommonGen | MHA | 5.7560 | 4.6510 | 6.7180 | -5.9250 | -6.4300 | -5.2720 | -4.2520 |
| THA | 0.1352 | 0.0823 | 0.1719 | 364.3847 | 302.4176 | 420.1534 | 57.9292 | THA | 5.2287 | 4.3996 | 6.0161 | -5.6318 | -6.1313 | -4.9114 | -3.7457 | ||
| DCMHA | 0.1261 | 0.0754 | 0.1618 | 365.2419 | 298.4362 | 419.3781 | 79.9443 | DCMHA | 5.2754 | 4.3677 | 5.9989 | -5.6686 | -5.7876 | -4.9677 | -3.8115 | ||
| ColMHA | 0.1273 | 0.0748 | 0.1625 | 364.5126 | 297.2184 | 417.6439 | 58.1658 | ColMHA | 5.2210 | 4.3567 | 6.0294 | -5.6745 | -5.8728 | -4.9503 | -3.7936 | ||
| MMA | 0.1289 | 0.0767 | 0.1597 | 358.4291 | 291.4753 | 423.1847 | 55.6137 | MMA | 5.2952 | 4.3092 | 5.9861 | -8.0765 | -8.6621 | -7.3931 | -6.2185 | ||
| MoA | 0.1569 | 0.0981 | 0.2028 | 369.7253 | 298.3416 | 417.4832 | 88.2483 | MoA | 5.2918 | 4.2990 | 5.9834 | -5.6805 | -5.6899 | -4.9597 | -3.7899 | ||
| DAMCHA | 0.1232 | 0.0730 | 0.1569 | 314.5722 | 288.9400 | 411.5314 | 53.7560 | DAMCHA | 5.2204 | 4.3105 | 5.9788 | -5.6142 | -6.1651 | -4.9410 | -3.7417 | ||

Figure 3: (a) Distribution of BARTScore on WMT data. (b) Distribution of NLL on WMT data.
Text Generation Performance. DAMCHA achieves the best BARTScore-based generation quality on both WMT and CommonGen. On WMT, DAMCHA improves BARTScore from -8.4740 under MHA to -5.4451 and improves BARTScore@Top-50 from -5.3090 to -4.1410. Compared with recent attention variants, DAMCHA also obtains the best BARTScore and BARTScore@Top-50, although MMA achieves a lower NLL mean. This suggests that lower token-level likelihood does not necessarily translate into better sequence-level generation quality.
MMA enforces head diversity through fixed attention masks (global, local, forward, and backward patterns), which may reduce per-token prediction uncertainty and thus lower NLL, but its rigid structural constraints limit the model's ability to form flexible, context-sensitive attention patterns required for coherent long-range generation. BARTScore captures this distinction: MMA's forced diversity yields competitive NLL at the cost of substantially degraded holistic generation quality (BARTScore mean: -8.3875 for MMA versus -5.4451 for DAMCHA), precisely the dimension that DAMCHA's adaptive cross-head metric is designed to improve. On CommonGen, DAMCHA achieves the lowest NLL mean (5.2204), the best BARTScore mean (-5.6142), and the best BARTScore@Top-50 (-3.7417), further confirming the effectiveness of the proposed metric learning mechanism.
Performance in High Quality Generation A critical observation is that the improvement margins on Top-50 metrics are substantially larger than on average metrics. For instance, on WMT, BARTScore@Top-50 improves by 22.0% (-5.3090 to -4.1410) compared to 35.7% in average BARTScore. The improvements hold consistently across all tasks, suggesting that DAMCHA's input-adaptive metric learning particularly benefits the generation of high-quality, confident outputs where cross-head coordination is critical for capturing complex dependencies.

Figure 4: (a) Distribution of FID on CIFAR-10 data. (b) Distribution of MSE on data.CIFAR-10.
Table 2: Efficiency comparison with recent multi-head attention variants.
| Method | CIFAR-10 | CIFAR-100 | CommonGen | WMT | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Mem. | GFLOPs | Lat.(ms) | Mem. | GFLOPs | Lat.(ms) | Mem. | GFLOPs | Lat.(ms) | Mem. | GFLOPs | Lat.(ms) | |
| THA | 255.40 | 0.0797 | 3.494 | 255.40 | 0.0797 | 3.535 | 406.80 | 0.1845 | 3.611 | 1416.68 | 0.4698 | 7.299 |
| DCMHA | 292.71 | 0.0785 | 4.443 | 292.71 | 0.0785 | 4.499 | 463.36 | 0.1780 | 4.428 | 1650.30 | 0.4399 | 8.148 |
| ColMHA | 207.39 | 0.0765 | 3.576 | 207.39 | 0.0765 | 3.552 | 282.79 | 0.1699 | 3.529 | 903.74 | 0.4068 | 3.868 |
| MMA | 191.39 | 0.0755 | 16.677 | 191.39 | 0.0755 | 17.606 | 281.05 | 0.1678 | 25.863 | 923.74 | 0.4027 | 44.356 |
| MoA | 321.07 | 0.1101 | 4.078 | 321.07 | 0.1101 | 4.098 | 484.35 | 0.2538 | 4.095 | 1649.67 | 0.6417 | 6.770 |
| DAMCHA | 204.70 | 0.0786 | 3.868 | 196.57 | 0.0786 | 3.843 | 271.23 | 0.1552 | 3.844 | 866.92 | 0.3586 | 3.895 |
Figure 3 visualizes the distribution shifts on WMT samples. The BARTScore distribution (Figure 3(a)) shows a similar rightward shift with reduced variance. The NLL distribution (Figure 3(b)) of DAMCHA is notably tighter and shifted leftward compared to MHA, with the mode moving from approximately 5.8 to 5.2. Figure 4 visualizes the distribution shifts on the CIFAR-10 dataset and further shows that, under DAMCHA, the distributions of both MSE and FID are consistently more favorable than those obtained with MHA. These distributional changes indicate that DAMCHA not only improves average performance but also reduces uncertainty across the entire sample space, leading to more reliable generation quality. Additional distribution visualizations on CIFAR-100 and CommonGen are provided in Appendix E. We also visualize the evolution CHM during training in Appendix F. The results confirms that DAMCHA progressively learns to coordinate attention heads in input-dependent ways, moving beyond the block-diagonal constraint of standard MHA to a full Mahalanobis-like metric over the joint head space.
5.2 Efficiency and Computational Cost
We further evaluate DAMCHA and the baselines in terms of memory usage, GFLOPs, latency, and throughput. The results are reported in Table 2.
Image Generation Tasks. DAMCHA requires memory usage comparable to ColMHA and lower than THA, DCMHA, and MoA. For CIFAR-10, DAMCHA uses 0.0786 GFLOPs, which are very close to those of the best-performing baseline, MMA, while achieving substantially better FID and FID@Top-50. On CIFAR-100, DAMCHA similarly maintains low memory usage and competitive latency while delivering the best generation quality. Although THA and ColMHA achieve slightly higher throughput on some image settings, their generation metrics are consistently worse than DAMCHA, indicating that DAMCHA provides a better quality–efficiency balance.
Text Generation Tasks. The efficiency advantage becomes more pronounced on text generation tasks. On WMT, DAMCHA uses 866.92 memory units and 0.3586 GFLOPs, which are lower than THA, DCMHA, ColMHA, MMA, and MoA. It also achieves much lower latency than THA, DCMHA, MMA, and MoA. On CommonGen, DAMCHA also uses substantially less memory than THA, DCMHA, and MoA while maintaining competitive latency and throughput. These results show that DAMCHA's improvements are not simply obtained by increasing model size or computation, but are mainly attributable to the proposed cross-head metric learning design.
5.3 Ablation Study
Metric Learning & Stack-Wise Sharing. We first ablate the two key innovations of DAMCHA: (1) the input-adaptive metric generator and (2) the stack-wise sharing mechanism. Table 4 presents results under three configurations: w/o +share removes both components, reducing DAMCHA to a static, unshared cross-head metric per-layer; w/o share retains input-adaptivity but uses layer-specific generators; and DAMCHA with both mechanisms.
The results demonstrate that both components are critical. Removing both and sharing leads to the largest degradation—on CIFAR-10, FID@Top-50 increases by (from 65.132 to 76.554), while average FID degrades by only . This substantial gap confirms that input-adaptive metric learning is particularly crucial for high-quality generation. The w/o share variant shows moderate degradation, with FID@Top-50 increasing by on CIFAR-10, indicating that independent per-layer causes overfitting and instability. Across all datasets, the pattern is consistent: removing input-adaptivity causes larger performance drops on Top-50 metrics than on average metrics. On
Table 3: Ablation on the capacity of the standard DAMCHA's at different depth, and inference using full-, diagonal-only, and off-diagonal-only metric matrices. Within each row (fixed setting and dataset), the best layer is highlighted in red bold and the worst layer in blue for each metric block.
| Setting | Dataset | FID@Top-50 / BART@Top-50 | FID / BART | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1-layer | 3-layer | 5-layer | 7-layer | 9-layer | 1-layer | 3-layer | 5-layer | 7-layer | 9-layer | ||
| DAMCHA | CIFAR-10 | 77.97 | 75.79 | 71.07 | 74.07 | 58.64 | 250.35 | 231.52 | 234.37 | 229.09 | 229.84 |
| CIFAR-100 | 65.20 | 60.82 | 57.64 | 52.14 | 50.29 | 275.80 | 240.98 | 221.85 | 237.57 | 217.89 | |
| WMT | -5.26 | -5.14 | -5.08 | -4.98 | -4.51 | -7.71 | -7.27 | -6.00 | -6.32 | -5.61 | |
| CommonGen | -4.97 | -4.90 | -4.62 | -4.84 | -4.60 | -7.83 | -6.53 | -7.65 | -6.90 | -6.20 | |
| Diagonal-only | CIFAR-10 | 102.51 | 105.05 | 108.505 | 98.703 | 112.856 | 248.38 | 233.05 | 235.17 | 233.485 | 239.609 |
| CIFAR-100 | 85.763 | 69.73 | 76.102 | 59.685 | 61.945 | 275.535 | 227.707 | 236.587 | 231.397 | 237.241 | |
| WMT | -6.218 | -6.043 | -5.622 | -5.457 | -5.618 | -7.186 | -7.411 | -7.070 | -7.854 | -7.859 | |
| CommonGen | -6.068 | -5.213 | -5.336 | -4.865 | -5.557 | -7.674 | -6.770 | -7.612 | -7.039 | -6.956 | |
| Off-diagonal-only | CIFAR-10 | 97.318 | 140.37 | 87.217 | 97.647 | 126.921 | 245.87 | 252.75 | 250.201 | 249.907 | 241.249 |
| CIFAR-100 | 91.10 | 104.128 | 105.026 | 97.144 | 72.746 | 268.725 | 246.883 | 247.715 | 250.512 | 236.142 | |
| WMT | -6.892 | -6.101 | -6.335 | -5.997 | -6.488 | -8.095 | -7.140 | -8.112 | -6.957 | -8.119 | |
| CommonGen | -5.10 | -5.681 | -5.954 | -5.2457 | -5.854 | -6.926 | -8.626 | -8.913 | -7.154 | -8.467 | |
CommonGen, BARTScore@Top-50 degrades by without compared to only degradation in average BARTScore. Moreover, we provide a visualized gradient-flow analysis in Appendix G to illustrate how our stack-wise sharing improves learning performance.
Table 4: Ablation results. Here, is implemented as an MLP. Blue indicates the relative degradation w.r.t. DAMCHA (in %).
| Dataset | Variant | Metric | Metric@Top-50 |
|---|---|---|---|
| CIFAR-10 (FID ↓) | w/o +share | 233.038 ↓-2.37% | 76.554 ↓-17.59% |
| w/o share | 228.961 ↓-0.58% | 77.851 ↓-19.59% | |
| DAMCHA | 227.641 | 65.132 | |
| CIFAR-100 (FID ↓) | w/o +share | 229.467 ↓-8.66% | 61.950 ↓-15.25% |
| w/o share | 234.296 ↓-10.95% | 57.934 ↓-7.77% | |
| DAMCHA | 211.290 | 53.756 | |
| WMT (BARTScore ↑) | w/o +share | -6.868 ↓-10.54% | -4.972 ↓-6.43% |
| w/o share | -6.932 ↓-11.57% | -4.930 ↓-5.54% | |
| DAMCHA | -6.213 | -4.672 | |
| CommonGen (BARTScore ↑) | w/o +share | -7.321 ↓-26.77% | -4.784 ↓-13.99% |
| w/o share | -6.814 ↓-17.99% | -4.817 ↓-14.78% | |
| DAMCHA | -5.775 | -4.196 |
Depth-wise Metric Learning & Cross-Head Learning. To analyze how metric learning strength affects learning performance and to verify the respective contributions of diagonal and off-diagonal blocks, we conduct three experiments: (1) standard DAMCHA using the full metric matrix, (2) diagonal-only inference where we zero out all off-diagonal blocks for , and (3) off-diagonal-only inference where we zero out all diagonal blocks. For each setting, we evaluate the performance of with different capacities (with 1, 3, 5, 7, 9 hidden layers).
Table 3 reveals two key findings. First, deeper layers consistently achieve better performance
under the standard DAMCHA setting. For example, on CIFAR-10, FID@Top-50 improves from 77.97 at layer 1 to 58.64 at layer 9, while the average FID decreases from 250.35 to 229.84. This trend is consistent across all datasets, confirming that later layers learn increasingly task-relevant metric transformations. This hierarchical pattern aligns with the metric matrix evolution shown in Figure 8, where deeper layers develop more specialized interaction structures. These results indicate that appropriately designed metric learning is necessary for enhancing the expressive power of model.
Second, the diagonal-only inference results indicate that the block-diagonal constraint imposed by standard MHA is indeed limiting. Compared with full DAMCHA, diagonal-only inference exhibits a substantial performance degradation, particularly on the Top-50 metrics. On CIFAR-10, even the best diagonal-only configuration (layer 7, FID@Top-50 = 98.703) performs worse than the weakest full DAMCHA configuration (layer 1, FID@Top-50 = 77.97). Moreover, off-diagonal-only inference performs significantly worse than both full and diagonal-only metrics. This observation suggests that the data inherently contains interactions at cross-head level, and that cross-head interactions modeled through off-diagonal blocks are essential for capturing complex dependencies. More visualized results on metric geometry in ablations are presented in Appendix H.
5.4 Autoregressive Generation with GPT-2
We apply DAMCHA to the GPT-2 and conduct token-level pretraining experiments on three datasets: Enwik8 (100M characters of Wikipedia text available at https://huggingface.co/google/reformer-enwik8.), Text8 (100M characters of cleaned Wikipedia, available at https://huggingface.co/datasets/afmck/text8), and Mix (200M characters, a 50-50 mixture of
Enwik8 and Text8). All models have 12 layers, 12 attention heads, model dimension 768, and are trained for 100K steps with batch size 64, context length 512, and learning rate . We report cross-entropy loss and perplexity (PPL) on held-out validation sets. Since DCMHA achieves the best performance among all baselines, we report only the comparison results against DCMHA and MHA.
Table 5 demonstrates that DAMCHA consistently outperforms both MHA and DCMHA across all three datasets. Notably, the gains are largest on the Mix dataset, where DAMCHA achieves and loss reduction over MHA and DCMHA respectively. This is consistent with DAMCHA's design rationale: the Mix dataset's heterogeneous semantic patterns demand cross-head coordination that MHA's block-diagonal structure cannot provide and DCMHA only partially addresses, while DAMCHA dynamically reconfigures its attention geometry to match the local context. Since DCMHA achieves the best performance among all baselines in the main generation experiments (Table 1), we focus our comparison on MHA and DCMHA to highlight the most informative contrast; the remaining baselines follow the same relative ordering observed in Section 5.1.
5.5 Discriminative Evaluation with Vision Transformers
We evaluate DAMCHA on ImageNet-1K classification using ViT-S/16 (12 layers, 6 heads, dimension 384, 22M parameters). Models are trained for 500 epochs with batch size 1024, learning rate 0.001, and standard augmentation. We report Top-1 and Top-5 accuracy at epochs 100 and 500 [43]. Table 6 shows that DAMCHA consistently outperforms both MHA and DCMHA baselines. DAMCHA achieves the highest accuracy across all evaluation points. At epoch 100, it obtains Top-1 and Top-5 accuracy, outperforming both MHA and DCMHA and indicating faster early-stage convergence. At epoch 500, DAMCHA further improves to Top-1 and Top-5 accuracy, maintaining consistent advantages over MHA and DCMHA. Although DCMHA narrows the gap after longer training, DAMCHA remains the best-performing model on all reported metrics. The larger early gap between DAMCHA and DCMHA suggests that DAMCHA's dynamic head coordination enables more efficient feature extraction from the start of training. While DCMHA narrows the gap with extended training, DAMCHA maintains advantages in both convergence speed and final performance across all metrics. Following the focused comparison strategy of Section 5.1, we report results against MHA and DCMHA, the strongest baseline across the generation experiments.
Table 5: Token-level pretraining results. Lower is better for cross-entropy loss and PPL. Red ↑ denotes DAMCHA's relative improvement over DCMHA (in %).
| Dataset | Cross-entropy loss ↓ | PPL ↓ | ||||
|---|---|---|---|---|---|---|
| MHA | DCMHA | DAMCHA | MHA | DCMHA | DAMCHA | |
| Enwik8 | 1.07 | 1.05 | 2.90 | 2.86 | ||
| Text8 | 1.06 | 1.05 | 2.88 | 2.86 | ||
| Mix | 1.09 | 1.08 | 2.98 | 2.94 | ||
5.6 Experiments with Synthetic Tasks
Table 6: Results on ImageNet-1K classification.
| Model | Top-1 | Top-5 | ||
|---|---|---|---|---|
| epoch 100 | epoch 500 | epoch 100 | epoch 500 | |
| MHA | 69.02% | 79.51% | 88.68% | 94.68% |
| DCMHA | 67.90% | 81.70% | 88.71% | 95.00% |
| DAMCHA | 70.93% | 82.10% | 89.71% | 96.23% |
To further understand the mechanism underlying DAMCHA's improvements, we design two synthetic tasks that explicitly require coordinated attention across multiple subspaces. These controlled experiments reveal that DAMCHA's advantage grows with the strength of cross-subspace entanglement: DAMCHA's relative gain increases and scales with feature dimensionality in the classification task. Crucially, when cross-subspace interactions are weak or absent, DAMCHA remains competitive with MHA, confirming that the adaptive cross-head metric incurs no penalty in simpler settings. These results provide controlled evidence that DAMCHA's improvements on real-world benchmarks are driven by its ability to model dependencies that span multiple attention heads, rather than by an increase in parameter count or computational cost. Full experimental details and results are provided in Appendix I. Computational resource details are reported in Appendix J, and a mechanistic discussion of DAMCHA's advantages over competing baselines is provided in Appendix K.
6 Conclusion
This paper proposes a novel attention mechanism, DAMCHA. By lifting both the block-diagonal and input-independent constraints of MHA, DAMCHA generalizes it into a data-adaptive metric learning framework. This formulation enables dynamic reconfiguration of attention geometry and explicit cross-head interaction modeling, providing significantly enhanced representational and approximation capabilities. Extensive experiments consistently demonstrate that DAMCHA delivers stronger performance, with particularly pronounced gains on high-quality and high-confidence samples. These results confirm that learning input-adaptive cross-head metrics for attention effectively enhances the representational capacity of Transformers, making DAMCHA well suited for complex dependency modeling and generative tasks.
References
[1] A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, I. Polosukhin, Attention is all you need, in: Proceedings of the 31st International Conference on Neural Information Processing Systems, NIPS'17, Curran Associates Inc., Red Hook, NY, USA, 2017, pp. 6000–6010.
[2] P. Michel, O. Levy, G. Neubig, Are sixteen heads really better than one?, in: Advances in Neural Information Processing Systems, Vol. 32, Curran Associates, Inc., 2019, pp. 14014–14024.
[3] L. Liu, J. Liu, J. Han, Multi-head or single-head? an empirical comparison for transformer training, arXiv preprint arXiv:2106.09650ACL ARR 2022 February Blind Submission (2021).
[4] T. Ruan, S. Zhang, Towards understanding how attention mechanism works in deep learning, arXiv preprint arXiv:2412.18288 (2024).
[5] Y. Shen, E. M.-K. Lai, M. Mohaghegh, Effects of similarity score functions in attention mechanisms on the performance of neural question answering systems, Neural Processing Letters 54 (3) (2022) 2283–2302.
[6] J.-H. Kim, J. Jun, B.-T. Zhang, Bilinear attention networks, in: Proceedings of the 32nd International Conference on Neural Information Processing Systems, NIPS'18, 2018, pp. 1571–1581.
[7] Y. Bian, J. Huang, X. Cai, J. Yuan, K. Church, On attention redundancy: A comprehensive study, in: Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, 2021, pp. 930–945.
[8] S. Liu, H. Peng, Z. Zhang, Z. Chen, Y. Guo, Multi-head low-rank attention, in: NeurIPS 2025 Workshop on Efficient Reasoning, 2025.
[9] C. Shen, J. Kim, L. Wang, Scalable large-margin mahalanobis distance metric learning, IEEE Transactions on Neural Networks 21 (9) (2010) 1524–1530.
[10] J. Liu, Y. Qiao, Mahalanobis distance-based kernel supervised machine learning in spectral dimensionality reduction for hyperspectral imaging remote sensing, International Journal of Distributed Sensor Networks 16 (11) (2020).
[11] Y. Zhao, C. Thrampoulidis, Why loss re-weighting works if you stop early: Training dynamics of unconstrained features, in: ICML 2025 Workshop on Methods and Opportunities at Small Scale, 2025.
[12] S. Zhong, W. Ruan, M. Jin, H. Li, Q. Wen, Y. Liang, Time-VLM: Exploring multimodal vision-language models for augmented time series forecasting, in: Forty-second International Conference on Machine Learning, 2025.
[13] H. Zhang, Q. Jin, T. Hartvigsen, M. Udler, M. Ghassemi, A pipeline for interpretable clinical subtyping with deep metric learning, in: ICML 3rd Workshop on Interpretable Machine Learning in Healthcare (IMLH), 2023.
[14] A. Galassi, M. Lippi, P. Torroni, Attention in natural language processing, IEEE Transactions on Neural Networks and Learning Systems 32 (10) (2021) 4291–4308.
[15] S. Chaudhari, V. Mithal, G. Polatkan, R. Ramanath, An attentive survey of attention models, ACM Transactions on Intelligent Systems and Technologies 12 (5) (2021) 1–32.
[16] S. Khan, M. Naseer, M. Hayat, S. W. Zamir, F. S. Khan, M. Shah, Transformers in vision: A survey, ACM Computing Surveys 54 (10s) (2022) 1–41.
[17] J. Merullo, C. Eickhoff, E. Pavlick, Talking heads: Understanding inter-layer communication in transformer language models, in: The Thirty-eighth Annual Conference on Neural Information Processing Systems, 2024.
[18] J.-B. Cordonnier, A. Loukas, M. Jaggi, Multi-head attention: Collaborate instead of concatenate (2021).
[19] D. Xiao, Q. Meng, S. Li, X. Yuan, Improving transformers with dynamically composable multi-head attention, in: Proceedings of the 41st International Conference on Machine Learning, Vol. 235 of Proceedings of Machine Learning Research, PMLR, 2024.
[20] Z. Zhang, N. Shao, C. Gao, R. Miao, Q. Yang, J. Shao, Mixhead: Breaking the low-rank bottleneck in multi-head attention language models, Knowledge-Based Systems 240 (C) (2022) 108075.
[21] Q. Guo, X. Qiu, X. Xue, Z. Zhang, Low-rank and locality constrained self-attention for sequence modeling, IEEE/ACM Transactions on Audio, Speech, and Language Processing 27 (12) (2019) 2213–2222.
[22] S. Bhojanapalli, C. Yun, A. S. Rawat, S. J. Reddi, S. Kumar, Low-rank bottleneck in multi-head attention models, arXiv preprint arXiv:2002.07028 (2020).
[23] V. N. Karkaria, D. Lee, Y.-P. Chen, Y. Yu, W. Chen, ASNO: An interpretable attention-based spatio-temporal neural operator for robust scientific machine learning, in: ICML 2025 Workshop on Reliable and Responsible Foundation Models, 2025.
[24] M. Yang, A. Feng, B. Xiong, J. Liu, I. King, R. Ying, Enhancing LLM complex reasoning capability through hyperbolic geometry, in: ICML 2024 Workshop on LLMs and Cognition, 2024.
[25] N. Shazeer, Z. Lan, Y. Cheng, N. Ding, L. Hou, Talking-heads attention, arXiv preprint arXiv:2003.02436 (2020).
[26] J.-B. Cordonnier, A. Loukas, M. Jaggi, Multi-head attention: Collaborate instead of concatenate, arXiv preprint arXiv:2006.16362 (2020).
[27] X. Zhang, Y. Shen, Z. Huang, J. Zhou, W. Rong, Z. Xiong, Mixture of attention heads: Selecting attention heads per token, in: Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing, Association for Computational Linguistics, 2022, pp. 4150–4162.
[28] H. Cui, S. Iida, P.-H. Hung, T. Utsuro, M. Nagata, Mixed multi-head self-attention for neural machine translation, in: Proceedings of the 3rd Workshop on Neural Generation and Translation, Association for Computational Linguistics, 2019, pp. 206–214.
[29] Y. Li, J. Wang, X. Dai, L. Wang, C.-C. M. Yeh, Y. Zheng, W. Zhang, K.-L. Ma, How does attention work in vision transformers? a visual analytics attempt, arXiv preprint arXiv:2303.13731 (2023).
[30] S. Jo, G. Jang, H. Park, Gmar: Gradient-driven multi-head attention rollout for vision transformer interpretability, in: Proceedings of the 2025 IEEE International Conference on Image Processing, 2025, pp. 582–587.
[31] G. Han, S. Shen, Research on chatglm-based tower machine intelligent q&a system with cross-layer shared dynamic attention, in: Proceedings of the 2025 7th International Conference on Natural Language Processing, 2025, pp. 200–204.
[32] Y.-H. Lan, Gateformer: Advancing multivariate time series forecasting via temporal and variate-wise attention with gated representations, in: 1st ICML Workshop on Foundation Models for Structured Data, 2025.
[33] X. Wang, Y. Hua, E. Kodirov, G. Hu, N. M. Robertson, Deep metric learning by online soft mining and class-aware attention, in: Proceedings of the Thirty-Third AAAI Conference on Artificial Intelligence, 2019, pp. 6129–6136.
[34] X. Liu, Z. Guo, J. You, B. V. K. V. Kumar, Dependency-aware attention control for image set-based face recognition, IEEE Transactions on Information Forensics and Security 15 (2020) 1501–1512.
[35] Y. Tay, L. A. Tuan, S. C. Hui, Latent relational metric learning via memory-based attention for collaborative ranking, in: Proceedings of the 2018 World Wide Web Conference, 2018, pp. 729–739.
[36] Z. Yang, K. Wang, L. Ye, X. Yuan, Y. Wang, C. Yang, W. Gui, A difference metric attention with position distance-based weighting for transformer in data sequence modeling of industrial processes, IEEE Transactions on Industrial Informatics 21 (2) (2025) 1803–1812.
[37] Y. Huang, Z. Wen, Y. Chi, Y. Liang, How transformers learn diverse attention correlations in masked vision pretraining, in: ICML 2024 Workshop on Theoretical Foundations of Foundation Models, 2024.
[38] B. Koyuncu, T. N. Bauerschmidt, I. Valera, E-protran: Efficient probabilistic transformers for forecasting, in: ICML 2024 Workshop on Structured Probabilistic Inference & Generative Modeling, 2024.
[39] T. Y. Chen, Dynamic causal-graph memory: Structured retrieval for million-token reasoning, in: ICML 2025 Workshop on Long-Context Foundation Models, 2025.
[40] X. Liu, Z. Guo, J. You, B. V. K. V. Kumar, Attention control with metric learning alignment for image set-based recognition (2019).
[41] O. Bojar, C. Buck, C. Federmann, B. Haddow, P. Koehn, J. Leveling, C. Monz, P. Pecina, M. Post, H. Saint-Amand, R. Soricut, L. Specia, A. Tamchyna, Findings of the 2014 workshop on statistical machine translation, in: Proceedings of the Ninth Workshop on Statistical Machine Translation, Association for Computational Linguistics, Baltimore, Maryland, USA, 2014, pp. 12–58.
[42] B. Y. Lin, W. Zhou, M. Shen, P. Zhou, C. Bhagavatula, Y. Choi, X. Ren, Commongen: A constrained text generation challenge for generative commonsense reasoning, in: Findings of the Association for Computational Linguistics: EMNLP 2020, Association for Computational Linguistics, 2020, pp. 1823–1840.
[43] J. Deng, W. Dong, R. Socher, L.-J. Li, K. Li, L. Fei-Fei, Imagenet: A large-scale hierarchical image database, in: 2009 IEEE Conference on Computer Vision and Pattern Recognition, IEEE, 2009, pp. 248–255.
Appendix
A Further Illustration on Expressive Power and Advantages of CHM
The introduction of cross-head interactions significantly enhances representational flexibility. For example, when the similarity between two tokens depends on interactions between features residing in different subspaces, standard MHA may fail to capture such dependencies if those features are assigned to separate heads. The CHM directly models these interactions via the off-diagonal blocks , enabling explicit cross-subspace similarity estimation. From a theoretical standpoint, removing the block-diagonal constraint allows the attention score matrix to represent higher-rank correlation patterns. As a result, a single attention layer equipped with cross-head metrics can express information structures that would otherwise require multiple stacked layers in standard MHA, leading to more efficient and powerful representation learning.
For our adaptive learning of CHM, the formulation can be interpreted as introducing a form of conditional metric learning, where the attention geometry is modulated by the current context. Rather than learning a single global notion of similarity, the model learns how to select or generate an appropriate metric given the input. Functionally, this resembles dynamic parameterization or conditional computation, in which a lightweight network produces part of the parameters of the main model to enable context-dependent behavior. From a representational standpoint, generating via explicitly introduces nonlinear, higher-order interactions into attention. The resulting attention score depends not only on the quadratic form , but also on the nonlinear transformation induced by . As such, the attention mechanism can be viewed as operating on higher-order polynomial features of , substantially enriching its function approximation and expressive capacity.
Several advantages are expected to be provided by our method Context-sensitive attention: The model can dynamically adjust its attention patterns across different inputs, improving sensitivity to contextual variations. Enhanced expressiveness: By allowing M to depend on X, the attention mechanism is no longer restricted to a fixed bilinear form, but instead realizes a composite mapping, which spans a significantly richer function class and can capture more complex dependencies. Reduced approximation bias: The adaptive mechanism alleviates the bias introduced by static parameters. Even if certain relationships are not learned as dominant global patterns during training, the model can still approximate them for specific inputs by generating specialized attention metrics, thereby reducing representational blind spots.
Asymmetric Design of Value Projection. A natural question concerns the asymmetric treatment of the query-key pathway versus the value pathway in DAMCHA: while replaces conventional linear query-key projections with an input-adaptive metric generator, the value projection retains the standard static linear form of MHA. This design is deliberate. The query-key pathway determines where attention is directed, that is, the similarity geometry, which varies most across contexts and benefits most from input adaptivity. The value projection, by contrast, determines what information is aggregated given fixed attention weights, a role that is well served by a static linear transformation in practice. Extending adaptivity to the value pathway would add computational overhead and optimization complexity without the same theoretical motivation: the expressiveness gains in Theorems C.1 and C.2 arise specifically from the adaptive similarity structure in the pre-softmax score, not from adaptive value representations. Exploring adaptive value projections in combination with DAMCHA's metric learning is nonetheless an interesting direction for future work.
B Data Flow and Tensor Shapes of DAMCHA
Figure 5 summarizes the end-to-end data flow of DAMCHA and MHA.
C Theoretical Analysis
In this section, we provide a theoretical justification for DAMCHA from two complementary perspectives. First, we show that the score-function class induced by DAMCHA strictly contains that of standard MHA. Second, we interpret both MHA and DAMCHA through the lens of metric learning.

Figure 5: Data flow and tensor shapes of DAMCHA (right, with the value/output projection shapes consistent with standard MHA)
and prove that input-adaptive cross-head metrics can reduce the irreducible metric mismatch incurred by a static global metric.
C.1 DAMCHA Strictly Generalizes MHA
We first formalize the attention score functions induced by standard MHA and DAMCHA. Let denote an input sequence, where is the sequence length and . For the -th head of standard MHA, the pre-softmax score matrix can be written as
where . Thus, each head in MHA corresponds to a static low-rank bilinear similarity metric and . For DAMCHA, the -th head is given by
where is generated by the input-dependent metric generator . The corresponding pre-softmax score matrix is
We define the score-function class induced by standard MHA as
Similarly, the score-function class induced by DAMCHA is defined as
We impose the following mild expressivity assumption on the metric generator.
Assumption 1. The metric generator is capable of representing constant matrix mappings. That is, for any collection of matrices , there exists a parameter such that , for all . This assumption is mild because a standard feedforward network or hypernetwork with bias terms can represent constant functions.
Theorem C.1 (Strict Function-Class Generalization of MHA). Suppose Assumption 1 holds and . Then the score-function class induced by standard MHA is strictly contained in that induced by DAMCHA:
Consequently, DAMCHA strictly generalizes MHA at the level of pre-softmax attention score functions.
Proof. We prove the result in two steps. Step 1: Inclusion. We first show that . By Assumption 1, DAMCHA can choose its generated cross-head metric blocks as constant matrices satisfying and , . Then the row-summed effective metric of the -th head becomes
It follows that
Then, every score function produced by MHA can be exactly reproduced by DAMCHA. This proves
Step 2: Strictness. We now show that the inclusion is strict. Since , there exists a matrix such that . By Assumption 1, DAMCHA can choose a constant effective metric for the first head as
For instance, this can be achieved by setting , , . Then DAMCHA induces the score function . Suppose, for contradiction, that this score function can also be represented by standard MHA. Then there must exist matrices , such that and for all admissible inputs . Equivalently, for all token vectors , , we have , which implies . However, since , we have
This contradicts
Then, the score function belongs to but not to . Hence,
The proof is complete.
C.2 Metric-Learning Advantage of Dynamic Cross-Head Metrics
The previous result establishes that DAMCHA strictly enlarges the attention score-function class. We next explain why this enlargement is meaningful from the perspective of metric learning.
The key difference between MHA and DAMCHA is that MHA learns a static global metric, whereas DAMCHA learns an input-adaptive metric. In heterogeneous data, the optimal similarity geometry may vary across contexts. A single global metric must average over these different local geometries and therefore suffers from an irreducible metric mismatch. DAMCHA can reduce this mismatch by conditioning the metric on the input.
Let denote a latent context variable with
The context C may represent different semantic regimes, syntactic patterns, visual structures, or distributional modes. We assume that, for each context c, there exists a context-specific optimal collection of effective attention metrics
where denotes the optimal effective metric for the -th head under context . Let denote a generic metric-learning loss associated with the effective metrics
This loss may correspond to attention alignment loss, contrastive metric loss, classification loss, or a downstream task loss induced by the attention scores. For each context c, define the conditional risk
We impose the following assumptions.
Assumption 2. For each context , the conditional risk has a unique minimizer , namely
Assumption 3. There exists a constant such that, for every context and every collection of metrics ,
This condition states that the conditional risk increases at least quadratically as the learned metric deviates from the context-specific optimal metric.
Assumption 4. The context C is identifiable from the input X, namely there exists a measurable function such that
Moreover, the DAMCHA metric generator is expressive enough to represent the context-dependent mapping
Assumption 4 formalizes the idea that the input contains sufficient information to determine the appropriate local similarity geometry. For standard MHA, the effective metric of each head is static and belongs to the low-rank query-key factorization class
Thus, the optimal static MHA risk is
In contrast, DAMCHA can use input-adaptive effective metrics
where each is generated through the cross-head metric matrix. The optimal DAMCHA risk is defined as
where ranges over the metric mappings representable by DAMCHA.
Theorem C.2 (Metric-Learning Risk Advantage of DAMCHA). Suppose Assumptions 2–4 hold. Then
Moreover,
Consequently, if there does not exist a single static collection of low-rank metrics , with , such that
then
Proof. We first characterize the best risk attainable by an input-adaptive metric. By Assumption 4, DAMCHA can represent the mapping . Since , this means that DAMCHA can select for each input. Therefore, the risk achieved by this oracle adaptive metric is
By the definition of , this becomes
Since is the infimum over all DAMCHA-representable mappings, and is one such mapping, we have
Now consider standard MHA. It must use a static collection of metrics
independent of the input context. For any such M, its excess risk over the adaptive oracle is
By Assumption 3,
Therefore,
Taking the infimum over all static MHA metrics , we obtain
The right-hand side is nonnegative, which proves . Furthermore, if no single static low-rank collection can simultaneously match all context-specific optimal metrics , then
Therefore, we have , which implies .
Theorem C.2 provides a metric-learning explanation for the advantage of DAMCHA. Standard MHA learns a single static metric shared by all inputs. When the data distribution contains multiple contexts with different optimal similarity geometries, this static metric must compromise among them and therefore suffers from an irreducible metric mismatch:
In contrast, DAMCHA can condition its cross-head metric matrix on the input and select a context-specific effective metric. Thus, DAMCHA behaves as an input-adaptive local metric learner, whereas MHA behaves as a static global metric learner.
D Computational Complexity Analysis of DAMCHA
D.1 Notation
Throughout this section we use the following symbols consistently.
| Symbol | Meaning |
|---|---|
| Sequence (context) length | |
| Model dimension | |
| Number of attention heads | |
| Per-head dimension, | |
| Per-head value dimension (set equal to unless noted) | |
| Depth (number of hidden layers) of the metric generator | |
| Hidden width of | |
| Number of stacked Transformer layers (depth of the network) |
All asymptotic statements use the standard notation and suppress constant factors. We analyse one DAMCHA attention layer and one standard MHA layer side-by-side, then aggregate to the full -layer stack.
D.2 Per-Layer Time Complexity
A single DAMCHA attention layer consists of five distinct computational stages.
Stage 1: Metric generator . Given the input sequence , the metric generator first computes a context summary via mean pooling, at cost . The resulting vector is passed through a -layer MLP with hidden width :
producing the flattened cross-head metric matrix . The dominant costs are:
Input projection: ,
hidden layers: ,
Output projection: .
Summing all stages of (including the pooling step):
Crucially, under stack-wise parameter sharing is shared across all layers and need only be evaluated once per forward pass, so its amortised per-layer cost is .
Stage 2: RowSum aggregation. The cross-head metric is an block matrix with blocks . For each query head we compute
This requires summing matrices of size for each of heads:
since .
Stage 3: Attention score computation. For each head , let be the -th positional slice of the input. The pre-softmax score matrix is
The two matrix products cost:
Summing over all h heads:
Stage 4: Softmax. Row-wise softmax over score matrices of size :
Stage 5: Value projection and output. This stage is structurally identical to standard MHA. Value projections cost per head; the attention-weighted sum costs per head; and the output projection costs . With and summing over heads:
Total per-layer cost of DAMCHA. Combining the five stages, and writing for the shared generator:
D.3 Comparison with Standard MHA
Standard MHA per layer involves:
Q, K projections (per head, h heads): ,
V projection : ,
(per head): ,
Softmax : ,
Output projection : .
Table 7 summarises the comparison. Three observations follow directly from this comparison.
Score computation is cheaper. The dominant cost of attention score formation in MHA is (from Q, K projections plus ). In DAMCHA, the corresponding cost is , a factor-of-h saving, because directly outputs the effective metric without the projection step.
Overhead of is amortised. Under stack-wise parameter sharing, is invoked once per forward pass regardless of N. As N grows (the typical setting for deep Transformers), its per-layer contribution tends to zero.
Table 7: Per-layer time complexity: DAMCHA vs. standard MHA. indicates the stage is shared across all layers and amortises to .
| Stage | MHA | DAMCHA |
|---|---|---|
| Q, K projections | —(replaced by ) | |
| Metric generator | — | |
| RowSum aggregation | — | |
| Attention scores | ||
| Softmax | ||
| V projection + output | ||
| Total (per layer) |
D.4 Parameter Count
Let denote the exact parameter count.
Standard MHA. Each layer contains projections for all heads and an output projection :
For an -layer stack: .
DAMCHA. Each layer retains and but discards and , which are superseded by :
The shared metric generator contributes a single parameter block:
Total for the -layer stack:
Net saving.
This saving is strictly positive whenever , i.e. . For the GPT-2 scale configuration (, , , ) the right-hand side evaluates to approximately 12.8, so DAMCHA has essentially the same parameter count as MHA at this scale and fewer parameters for larger . Concretely, DAMCHA achieves a reduction in attention-module parameters relative to MHA when and .
E Additional Distribution Plots for Sample Generation
Figures 4–7 show that DAMCHA consistently changes the shape of the generation-score distributions rather than only improving the average. Across datasets, DAMCHA tends to shift probability mass toward the high-score region and reduce the density of low-score samples, indicating fewer low-quality outliers. In addition, the KDE curves under DAMCHA are typically more concentrated, suggesting improved stability (smaller dispersion) in generation quality. These distribution-level patterns align with the main-text quantitative results and provide evidence that the gains are not driven by a small subset of samples.

Figure 6: Supplementary distribution plot on CIFAR-100.

Figure 7: Supplementary distribution plot on CommonGen.
F The Evolution of Cross-Head Metric Matrix during training
Figure 8 visualizes the learned cross-head metric matrices at different training stages on CIFAR-10. We show four representative layers (layer-0, 1, 2, 3) at epoch 1 (top row) and epoch 50 (bottom row). At epoch 1, the matrices exhibit relatively uniform structures with weak off-diagonal interactions. By epoch 50, three distinct patterns emerge: (1) Strong diagonal blocks: The diagonal blocks corresponding to show high activation values, indicating well-learned intra-head similarities that capture head-specific feature patterns. (2) Structured off-diagonal blocks: Systematic cross-head interactions appear in the off-diagonal regions, particularly in middle layers (layer-1, layer-2). These blocks encode how queries from one head measure similarity under the feature patterns of another head, implementing the cross-head cooperation mechanism. (3) Layer-specific specialization: Early layers (layer-0, layer-1) develop denser and more diverse off-diagonal structures, suggesting active cross-modal feature integration in shallow representations. Deeper layers (layer-2, layer-3) maintain sparser but more targeted interactions, focusing on task-specific head coordination. This hierarchical specialization aligns with the intuition that early layers perform general feature extraction while deeper layers implement task-specific reasoning.
G Gradient Flow Analysis for Stack-Wise Sharing
To understand how parameter sharing stabilizes training, Figure 9 visualizes the gradient contribution heatmaps of the cross-head metric matrix under two settings: (a) without sharing and (b) with the standard DAMCHA sharing mechanism. Each heatmap shows the norm of gradients flowing into each block of the metric matrix during training.
Without sharing (panel a), gradients are distributed unevenly across the matrix, with some blocks receiving disproportionately large updates (bright regions) while others remain nearly inactive (dark regions). This uneven flow leads to unbalanced learning where certain cross-head interactions dominate while others fail to develop. In contrast, with parameter sharing (panel b), gradients distribute more uniformly across the entire matrix. The diagonal blocks maintain strong but controlled gradients, while off-diagonal blocks show moderate and consistent activation. This balanced gradient

Figure 8: Cross-head metric matrix visualization on CIFAR-10. The top row shows the state of the cross-head metric matrix at epoch 1, and the bottom row shows the state at epoch 50.
flow prevents any single layer from learning degenerate or overly specialized metrics, promoting cooperative learning across layers.
The visualization explains the performance gap in Table 4: shared parameters act as an implicit regularizer, forcing all layers to reuse a consistent family of metric transformations. This constraint prevents layer-specific overfitting and encourages the model to learn generalizable cross-head interaction patterns. Qualitative contour-map comparisons across epochs are included in Appendix H (Fig. 10), supporting the ablation findings.
(a)

(b)
Figure 9: (a) Gradient contribution heatmap of the cross-head metric matrix when the sharing mechanism is disabled. (b) Gradient contribution heatmap of the cross-head metric matrix under the standard DAMCHA setting.
H Additional Visualizations for Ablation and Metric Geometry
Figure 10 provides a qualitative ablation comparison across training epochs for WMT dataset. The w/o variant tends to exhibit less coherent contour structures and slower stabilization over epochs, whereas DAMCHA forms clearer and more stable geometric patterns as training progresses. This supports the view that the input-adaptive generator helps shape a more structured and stable metric geometry.
Figure 11 further corroborates this observation from the perspective of the learned metric matrix M. Compared with the static design (w/o ), the DAMCHA surface typically appears more organized (with smoother variations and fewer irregular spikes), consistent with a better-conditioned metric landscape.

Figure 10: Contour-map visualizations across training epochs (Epoch 0/12/24/36/49). Top: w/o ; Bottom: DAMCHA.
(a)

(b)
Figure 11: 3D surface visualization of the learned metric matrix M. Left: w/o ; Right: DAM-CHA.
I Synthetic Tasks
In this section, we design two synthetic tasks (regression and classification) to more explicitly present the advantages and underlying mechanism of our cross-head metric learning framework: modeling dependencies that require coordinated attention across multiple subspaces.
We consider a feature space formed by 4 subspaces. Each subspace is constructed by a vector-valued variable, respectively, denoted by . Each and its data is generated following . We define the following 4-dimensional regression system
where is a within-subspace weight vector, is a cross-subspace interaction matrix. All the weight parameters are initialized by sampling from . When , the task reduces to independent within-subspace prediction. As increases, cross-subspace interactions become more critical, and DAMCHA's cross-head metric can provide advantages.
For a C-classes problem, we define a target classification system. The score for class c is computed as:
where is a class-specific cross-subspace interaction matrix. is constructed as: where are randomly initialized and . The final label is determined by label = where noise is added for regularization. controls the entanglement level (strength of cross-subspace dependencies).

Figure 12: Cross-subspace regression: DAMCHA vs. MHA. (a) comparison results (testing MSE) under different entanglement levels. (b) DAMCHA's relative advantage under different entanglement levels.

Figure 13: Cross-subspace classification: DAMCHA vs. MHA. (a) Comparison results (accuracy %) under different . (b) Relative improvement of DAMCHA over MHA across different .
For both systems, we train two 4-head Transformer models with head dimension 32. For the regression system, under , the model is trained for 10K steps with batch size 64. The model for the classification system is trained with 14K steps and batch size 128.
For regression task, we evaluate DAMCHA and MHA using testing mean square error (MSE). Figure 12(a) presents comparison results with error bars, which demonstrates clear advantages of DAMCHA. Figure 12(b) reveals a more nuanced picture by plotting DAMCHA's relative advantage over MHA. At , DAMCHA underperforms MHA by 1.7%, when only limited cross-subspace interaction is needed. As increases from 0.2 to 1, DAMCHA's advantage grows from -1.7% to +4.8%, confirming that the benefit scales with the strength of subspace entanglement.
For classification task, for comprehensive and robust evaluation, we vary , resulting in total dimensions from 16 to 80. Figure 13(a) provides accuracy comparison against , visually confirming DAMCHA's consistent advantage across all settings. It also reveals an important scaling property: as increases, both methods degrade, but DAMCHA degrades more slowly. This implies that DAMCHA's cross-head coordination becomes increasingly valuable in high-dimensional settings where MHA's independent heads cannot effectively capture the full feature space interactions. Figure 13(b) quantifies the relative improvement, further illustrating the advantages of DAMCHA.
The two synthetic experiments identify clear conditions under which DAMCHA provides advantage: (i) when the target dependencies explicitly involve interactions across feature subspaces that are assigned to different attention heads, (ii) such cross-subspace interactions are sufficiently strong (e.g., in the regression system), and (iii) the feature dimensionality is moderate to high (e.g., in the classification system), where richer representational capacity becomes critical. These controlled findings offer a principled explanation for DAMCHA's strong empirical performance on real-world benchmarks, where complex, multi-faceted dependencies naturally arise. In such settings, the ability to explicitly model cross-head interactions allows DAMCHA to capture dependencies. When the underlying data-generating process is relatively simple, or when meaningful dependencies can be captured within individual heads without requiring cross-head coordination, standard MHA may already be sufficient, leading to comparable generalization performance. This observation highlights that DAMCHA is most beneficial in scenarios where cross-subspace interactions are intrinsic to the task, while remaining competitive in simpler regimes.
J Computational Resources and Runtime Details
All experiments in this paper were conducted on a single server with the following hardware and software configuration:
• GPU: NVIDIA RTX 3090 (24 GB VRAM) × 1
• CPU: 12 vCPU Intel(R) Xeon(R) Platinum 8255C @ 2.50 GHz
• Operating System: Ubuntu 22.04
• Python: 3.12
• PyTorch: 2.7.0
• CUDA: 12.8
Per-Experiment Runtime. Table 8 summarizes the approximate wall-clock training time for each experimental setting.
Table 8: Approximate training time per experimental setting. All runs use a single RTX 3090 GPU.
| Experiment | Dataset | Steps / Epochs | Approx. Training Time |
|---|---|---|---|
| Decoder-only Transformer | CIFAR-10 | 50 epochs | ~3 h |
| CIFAR-100 | 50 epochs | ~3 h | |
| WMT14 | 50 epochs | ~5 h | |
| CommonGen | 50 epochs | ~4 h | |
| GPT-2 Pretraining | Enwik8 | 100K steps | ~8 h |
| Text8 | 100K steps | ~8 h | |
| Mix | 100K steps | ~10 h | |
| ViT-S/16 Classification | ImageNet-1K | 500 epochs | ~72 h |
| Synthetic Tasks | Regression / Classification | 10K–14K steps | <30 min |
K Comparison with Baseline Methods
Mechanistic Advantages over Competing Attention Methods. From a theoretical standpoint, the advantages of DAMCHA over all baseline methods can be understood through three independent but complementary mechanisms: the structural expansion of the metric feasible class, the dynamic adaptivity of the learned similarity geometry, and the rank enhancement induced by cross-head aggregation. No existing baseline addresses all three simultaneously, and the gap between DAMCHA and each competitor can be precisely traced back to which of these mechanisms it lacks. At the empirical level, these distinctions consistently translate into superior performance across all benchmark tasks, stemming from two fundamental innovations absent in every prior method: (i) learning the full cross-head metric matrix that explicitly captures inter-head interactions beyond the block-diagonal constraint of standard MHA, and (ii) parameterizing this metric as an input-dependent function, enabling the attention geometry to dynamically adapt to the local manifold structure of the data at inference time.
vs. MHA. Standard MHA imposes a block-diagonal restriction on the joint head-space metric, structurally zeroing out all off-diagonal interactions, fixing the metric after training, and capping the per-head rank at the projection dimension, thereby simultaneously introducing all three deficiencies that DAMCHA is designed to resolve. DAMCHA strictly generalizes MHA: MHA is exactly recoverable as a special case by setting all off-diagonal metric blocks to zero and using a constant generator, while the converse is provably false (). The resulting performance gap decomposes into two independent additive components: a structural gap from the enlarged metric feasible class, and a dynamic gap from input-adaptive metric generation, both of which are strictly positive under mild conditions on the input distribution. Concretely, MHA’s static metric can at best approximate the average attention geometry , whereas DAMCHA’s adaptive generator targets the pointwise optimum for every input, translating to a 31.1% relative reduction in FID@Top-50 on CIFAR-10 and a 35.7% improvement in BARTScore on WMT.
vs. THA. Talking-Heads Attention inserts learned linear projections across the head dimension immediately before and after the softmax, allowing attention weights to be redistributed across heads at the weight level. However, this operates entirely at the post-hoc aggregation level: the underlying per-head similarity metric remains unchanged, static, and rank-limited. From a metric-learning perspective, THA never modifies the similarity geometry itself; its cross-head interaction is confined to a linear remixing of already-formed attention patterns rather than a genuine coupling at the similarity-formation stage, and THA therefore inherits all three limitations of MHA in terms of metric expressiveness. DAMCHA, by contrast, intervenes directly at the metric level before any attention score is computed, and this structural distinction is reflected empirically: THA yields worse MSE, FID, and NLL than DAMCHA across all datasets while requiring substantially more memory (255.40 vs. 204.70 on CIFAR-10) and higher latency.
vs. DCMHA. DCMHA introduces input-dependent composition of attention score and weight matrices via a Compose function, making it the baseline that most closely approaches DAMCHA's dynamic adaptivity. The key theoretical distinction, however, is where the input-dependence is introduced: DCMHA's Compose function operates on scores already derived from fixed, low-rank per-head bilinear forms, reweighting and mixing existing scores but never escaping the rank ceiling imposed by the individual head projections. DAMCHA's adaptivity is applied directly to the metric that generates the scores, meaning the attention geometry itself is data-dependent before any score is produced. DCMHA can be understood as composing within a restricted space of attention patterns, whereas DAMCHA reconfigures the similarity space from which all patterns are drawn. The structural advantage of expressing full-rank, off-diagonal cross-head metrics therefore persists even when both methods employ similarly expressive input-dependent generators. Experimentally, DAMCHA outperforms DCMHA on all metrics in both the generation experiments and the GPT-2 pretraining experiments, with cross-entropy improvements of 1.90%–3.70% across Enwik8, Text8, and Mix, while also using less memory (204.70 vs. 292.71 on CIFAR-10) and achieving lower latency.
vs. ColMHA. Collaborative MHA addresses head redundancy by sharing key/query projections via Tucker tensor decomposition, providing a compact reparametrization. From a theoretical standpoint, however, the resulting model is entirely static: the shared projections are determined at training time and carry no mechanism for input-dependent adaptation, keeping the metric class within a subset of fixed bilinear forms. Moreover, the relief from the low-rank bottleneck that ColMHA obtains is a post-hoc algebraic correction applied to a pre-trained model, not a structural property of the architecture itself. DAMCHA achieves rank enhancement organically through the RowSum aggregation of cross-head metric blocks (with no reparametrization required) and simultaneously endows this richer metric class with input-adaptive generation from the outset. On both image and text generation tasks, DAMCHA achieves substantially better FID@Top-50 and BARTScore@Top-50 than ColMHA, confirming that static projection sharing cannot substitute for dynamic cross-head metric learning.
vs. MoA. Mixture of Attention Heads introduces token-level selectivity by routing each token to a sparse subset of heads via a learned gating network, providing a limited form of input-dependent adaptivity. However, routing operates at the output level by sparsely combining independently formed, low-rank attention distributions; each selected head still computes an independent Euclidean dot-product similarity within its own subspace, and there is no path by which the similarity geometry of one head can be influenced by or coordinated with that of another at the score-formation stage. MoA therefore provides no mechanism for modeling metric-level interactions between heads, which is precisely the coupling that DAMCHA encodes as a first-class structural property. This theoretical limitation is compounded by a practical one: the sparsity required by MoA incurs the highest memory footprint of all compared methods (321.07 on CIFAR-10 vs. 204.70 for DAMCHA) and the highest GFLOPs (0.1101 vs. 0.0786), without commensurate performance gains.
vs. MMA. Mixed Multi-Head Attention enforces head diversity by assigning fixed attention masks (global, local, forward, and backward) to different heads. From a theoretical perspective, this is a strict special case of MHA: the additional structural constraints on admissible attention patterns further reduce the effective function class rather than expanding it, making MMA theoretically weaker than standard MHA in terms of metric expressiveness. MMA's diversity is entirely predetermined and input-independent, and it does not interact with the similarity metric at all; it merely restricts which positions each head is permitted to attend to, without altering the underlying dot-product geometry. This rigidity becomes a critical liability on tasks requiring fine-grained, context-sensitive head coordination: while MMA achieves competitive NLL on WMT, it degrades significantly on BARTScore@Top-50 and collapses on CommonGen, precisely the settings where DAMCHA's adaptive cross-head metric excels.