---
title: "Head-wise Shareable Attention for Large Language Models (2024)"
description: "Head-wise shareable attention reduces weight storage by tying similar attention heads, with optional post-training to recover accuracy."
canonical: "https://research.elamur.ai/free/en/papers/cao-2024-head-wise-shareable-attention-large/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/) · [Constitution](https://md.constitution.elamur.ai/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/cao-2024-head-wise-shareable-attention-large/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2024](https://md.research.elamur.ai/free/en/papers/2024/) / Head-wise Shareable Attention for Large Language Models

# Head-wise Shareable Attention for Large Language Models

Paper · 2024 · Zouying Cao, Yifei Yang and Hai Zhao

**Authors:** [Zouying Cao](https://md.research.elamur.ai/free/en/authors/zouying-cao/), [Yifei Yang](https://md.research.elamur.ai/free/en/authors/yifei-yang/) and [Hai Zhao](https://md.research.elamur.ai/free/en/authors/hai-zhao/) · **Year:** 2024 · **Venue:** Findings of the Association for Computational Linguistics: EMNLP 2024 · **Licence:** [CC BY 4.0 (ACL Anthology)](https://creativecommons.org/licenses/by/4.0/)

Findings of the Association for Computational Linguistics: EMNLP 2024 · [licence](https://creativecommons.org/licenses/by/4.0/)

- [Publisher's page](https://aclanthology.org/2024.findings-emnlp.144/)
- [PDF](https://aclanthology.org/2024.findings-emnlp.144.pdf)
- [DOI 10.18653/v1/2024.findings-emnlp.144](https://doi.org/10.18653/v1/2024.findings-emnlp.144)

## Summary

A device can have enough computing power to run a language system and still lack the memory to hold its weights. The authors ask how much of that storage is necessary when different attention heads already behave similarly. An attention head uses learned weights to decide which tokens to attend to and what information to gather from them. In a Transformer, several heads perform this operation at each layer. The paper proposes letting selected heads in different layers use the same weights while continuing to operate at their original places in the network.

The authors first compare the attention patterns produced on translation and language-understanding examples. Some pairs of heads have much more similar patterns than the most similar pairs of whole attention layers. The authors also find that heads with similar patterns across datasets tend to have similar query and key weights, which help determine where the heads attend. Their method uses those two sets of weights to rank potential matches. For a selected match, it ties the query, key and value weights together as a unit. DirectShare does this immediately with the existing weights. PostShare first continues training on English Wikipedia, with an added penalty that encourages the selected weights to move closer together before tying.

The cost in accuracy depends on what is tested. With a 30% sharing target within attention, DirectShare retains 99.51% of the original average on the paper’s reasoning benchmarks for Llama2-7B and 99.21% for Llama2-13B. Reading comprehension and the examination benchmarks can be much more sensitive. At the same sharing target, Llama2-7B scores 70.67 on BoolQ before compression, 54.43 with DirectShare and 66.57 with PostShare after 0.5 training epoch. The improvement is uneven. At that checkpoint, C-Eval moves from 26.24 with DirectShare to 26.38 with PostShare, compared with 32.20 before compression.

The paper measures GPU memory during BoolQ inference, where attention-only DirectShare at the 30% target leaves Llama2-7B using 87.02% of its original GPU memory and Llama2-13B using 90.58%. The current implementation also generates fewer tokens per second in the paper’s speed test. These measurements put the contribution in practical terms. Head-wise sharing can reduce the memory needed to hold a pretrained system, and a short period of additional training can recover some of the accuracy lost in the process. How much accuracy comes back depends on the task and the training checkpoint.

## Deep dive: Head-wise Shareable Attention for Large Language Models

Head-wise shareable attention reduces weight storage by tying similar attention heads, with optional post-training to recover accuracy. · about 31 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### Which weights need their own storage?

A trained language system contains weights that its layers read during inference. When the system has billions of parameters, keeping those weights available can strain device storage and GPU memory. The introduction relates that problem to the growth in size discussed in work on [scaling laws](https://md.research.elamur.ai/free/en/concepts/scaling-laws/). Its examples range from smaller pretrained systems such as [BERT](https://md.research.elamur.ai/free/en/papers/devlin-2019-bert-pre-training-deep-bidirectional/) and [RoBERTa](https://md.research.elamur.ai/free/en/papers/liu-2019-roberta-robustly-optimized-bert-pretraining/) to the larger systems that motivate the compression study.

Weight sharing addresses a particular part of the storage problem. Suppose several operations read different arrays of learned numbers. If they can use the same array with an acceptable change in behavior, the system can keep a single set of numbers and use it repeatedly. Sharing therefore changes the number of distinct weights that must be held. The operations themselves can still occur at their original positions, each with its own input. A design that shares more weights can save more storage while also taking a larger chance that a useful distinction between the original operations disappears.

A central choice is how much of the network to treat as one unit. Tying a whole layer makes one decision for all the components in that layer. That can be convenient when designing a network to use the same weights repeatedly from the beginning. It is a broad intervention in an existing checkpoint, where different parts of a layer can have different degrees of resemblance to parts of other layers. A convincing match for one attention head gives little guidance about what to do with the remaining heads or with the feed-forward network in the same layer.

The paper separates storage from computation for this reason. A head can continue to compute a contribution to its layer even after it loses its private copy of the weights. This is particularly relevant when the deployment obstacle is fitting the system into memory. A benchmark that measures only task accuracy misses the resource benefit, and a memory measurement alone says little about the cost in accuracy or elapsed time. The design has to be understood in terms of what it reuses and what still runs.

#### How earlier work shared or removed parameters

The authors describe several routes to compression. Quantization reduces the precision used to represent weights. Pruning removes parts of the parameterization. Knowledge distillation trains a compressed system using information supplied by another system. The paper notes that some compression schemes become difficult to apply at large scale and that recovering accuracy can require substantial additional training. It also describes attention designs directed at efficiency, including [Reformer](https://md.research.elamur.ai/free/en/papers/kitaev-2020-reformer-efficient-transformer/), which uses sparsity in attention, and Lightformer, which combines weight transfer based on singular value decomposition with parameter sharing.

Earlier work had shared weights at several levels of a Transformer. In the paper’s account, Tied Transformer ties weights between the encoder and decoder used for translation. Another translation approach reuses a layer’s weights across the stack. The authors also describe an application of ideas from [ALBERT](https://md.research.elamur.ai/free/en/papers/lan-2019-albert-lite-bert-self-supervised/) to speech recognition. These examples establish that repeated use of a parameter can be designed around a task or around the organization of the network.

Layer-wise methods supply a more direct precedent. [Universal Transformer](https://md.research.elamur.ai/free/en/papers/dehghani-2018-universal-transformers/) shares weights across layers and uses a mechanism to determine when computation should halt. Subformer shares the middle layers while keeping the first and last layers independent. The paper also describes work that studies how to allocate a smaller collection of parameter sets to a larger collection of layer positions. That history makes the allocation question explicit. Even when a design has settled on how many sets of weights to keep, it still has to decide where each set will be used.

The authors cite earlier work associating identical weights across layers with training instability and performance deterioration. They also point out that established cross-layer methods were often developed around smaller pretrained systems. Their question starts from a large checkpoint that has already learned different parameters for different positions. They want a sharing rule that can take advantage of that existing structure and can be applied with little or no further training.

#### Why look at heads?

Within a layer, a multi-head attention block maintains several separate ways to relate tokens. Each head has its own learned projections, and the resulting heads can behave differently even though they receive the same layer input. Earlier work cited in the paper treats that diversity as meaningful, including work on [attention visualization](https://md.research.elamur.ai/free/en/papers/vig-2019-multiscale-visualization-attention-transformer-model/). A sharing decision made at the level of a head lets the rest of the block keep its own weights. It also allows different heads in a layer to obtain their weights from different earlier layers.

The immediate precedent is research on attention-map reuse. An attention map records the attention assigned from token positions to other token positions on a particular input. Previous studies had observed similar maps across layers, especially neighboring layers, and explored reusing them. That line of work asks whether a pattern already computed at one location can serve another. Head-wise weight sharing takes the observation as evidence about where to look for redundant parameters. The compressed system still computes attention at each head position, using that position’s current input.

The difference matters when moving from a demonstration to a compression rule. Similarity between two attention maps is a property of the heads on the examples used to produce those maps. A fixed pair of shared weights has to serve inputs beyond those examples. The authors describe earlier approaches that learn how to share and approaches that train a network from scratch with a uniform sharing arrangement. For the design studied here, they instead look for a signal in the pretrained weights that can identify compatible heads directly. The next step is to test whether this signal has a plausible relationship to actual attention behavior.

### The method, step by step

#### From an attention map to a candidate match

An attention head begins with the representations of the tokens reaching its layer. It transforms those representations into queries, keys and values. A query is used to score possible positions for a given token. A key is what the query is compared with. A value is the information available to be gathered from a position. The attention map describes the weighting of positions. The output of the head also depends on the values to which those weights are applied.

This gives the authors two places to look for resemblance. They can give the system example sequences and compare the maps that heads produce, or they can compare the learned matrices that the heads use. The former tests behavior on actual inputs. The latter gives them a way to search the checkpoint itself. What ties the two together is the role of the query and key projections in producing the scores. If heads have similar projections there, it is reasonable to investigate whether their maps also resemble one another.

The paper uses cosine similarity for the initial map comparison. It compares the direction of two arrays of scores after accounting for their magnitudes. The layer-level expression can be written with the entries of each map arranged in the same order as a vector.

```
S_cos(Aₚ, A_q) = (Aₚᵀ A_q) / (‖Aₚ‖ ‖A_q‖)
```

Here `S_cos` is cosine similarity. `Aₚ` and `A_q` are the attention maps being compared, with `p` and `q` identifying their layers in this expression. The superscript `ᵀ` transposes the first vector so that the multiplication in the numerator is their dot product. Each pair of norm bars gives the length of its vector. The slash divides the dot product by the product of those lengths. At the head level the same calculation is applied to maps for individual heads. The index `q` here labels a map and has a different role from the query label used for a projection below.

The visualization draws examples from WMT14 English–French translation, [CommonsenseQA](https://md.research.elamur.ai/free/en/papers/talmor-2019-commonsenseqa-question-answering-challenge-targeting/) and WSC. In the layer comparison, the paper uses the last layer to illustrate the search for similar layers. In the head comparison, it looks for heads that most resemble a particular head in that layer. The best layer matches reach roughly 0.90 cosine similarity, and several head pairs reach almost 0.99. These values describe the strong matches found in the comparison. The visualization also shows that some matches recur when the task changes, even though the full pattern of similarity can vary.

The weight comparison starts from this recurrence. One way to build a sharing rule would be to rank pairs by their maps on each dataset and then choose matches that appear across datasets. That requires running the system on those datasets, extracting maps and deciding what counts as enough agreement. The paper instead looks at the cosine similarity of the query and key weights put together. In the visualization, the strongest matches by that criterion overlap with heads that are similar by their maps on multiple tasks. The appendix then measures the agreement more systematically.

#### Representing a head and scoring a pair

For the formal description of multi-head attention, the paper writes the input as a matrix with one row per token. The weights of a head project those rows into the spaces used for queries, keys and values.

```
X ∈ ℝ^{L×D}
```

`X` is the input to the attention block. `∈` means that `X` belongs to the indicated set of matrices, and `ℝ` means that the entries are real numbers. `L` is the number of input tokens, `D` is the width of the input representation, and `×` separates the row and column dimensions. The algorithm later uses `L` for the number of network layers. Its use here is local to the description of the input.

The three weight matrices all have input dimension `D`. Their output dimensions are `d_q` for the query, `d_k` for the key, and `d_v` for the value. The paper sets `d_k` equal to `d_q`, so that the query and key can be compared in the same space. The query matrix for head `i` is `Wᵢ^q`, the key matrix is `Wᵢ^k`, and the value matrix is `Wᵢ^v`. Applying the corresponding matrix to `X` produces that head’s queries, keys or values. A second head at another layer applies its own matrices to the representations available at that layer.

The paper first defines a general interface for scoring a pair. That interface covers strategies that judge each projection by itself as well as strategies that give a single score to a complete head match.

```
mᵢⱼ^∗ = Match(Wᵢ^∗, Wⱼ^∗),  ∗ ⊆ {q, k, v}
```

`mᵢⱼ^∗` is the matching score for heads `i` and `j` under the projection choice marked by `∗`. `Wᵢ^∗` and `Wⱼ^∗` stand for the selected weights of the two heads. `Match` is the function that turns those weights into a score, with larger values indicating more desirable matches. `⊆` expresses that the choice comes from the set in braces. The letters `q`, `k` and `v` refer to query, key and value. In the paper’s notation `∗` can designate an individual weight matrix or the choice of matrices used jointly by a matching rule.

The rule used in both DirectShare and PostShare takes the query and key matrices, concatenates them for each head, and compares the resulting arrays. Concatenation places the entries of both matrices into a common representation in a consistent order. Every pair receives one score, which applies to all its projections.

```
mᵢⱼ^q = mᵢⱼ^k = mᵢⱼ^v = S_cos(Wᵢ^q ‖ Wᵢ^k, Wⱼ^q ‖ Wⱼ^k)
```

`mᵢⱼ^q`, `mᵢⱼ^k` and `mᵢⱼ^v` are the scores associated with the query, key and value projections of the pair. The equality signs assign them the same value. `S_cos` is the cosine comparison, with the corresponding entries in each concatenated array treated as vector entries. `‖` between matrices means concatenation here. `Wᵢ^q` and `Wᵢ^k` supply the query and key matrices for head `i`, and `Wⱼ^q` and `Wⱼ^k` do the same for head `j`. The value matrix participates in the eventual tie under this score.

The distinction between scoring and tying is important. The query and key matrices supply the evidence for choosing a partner because they help determine the attention pattern. The intervention itself ties the value projection along with them. A procedure that independently scores and substitutes all three projections can take the query from one earlier head, the key from another and the value from a third. The joint rule keeps these components together as they were learned in the head whose weights are retained. The paper compares those choices experimentally.

Selecting and tying attention heads The steps in order.

#### DirectShare changes the checkpoint immediately

DirectShare begins at the layer after the first one. For each head there, and for each head in the layers that follow, it considers every head in an earlier layer. It evaluates the pair by the query–key cosine rule and keeps the highest-scoring candidate for that later head. The candidate record contains both layer and head positions along with the score. The first layer can supply weights to a match but has no earlier layer from which to obtain them.

The procedure then sorts these best matches together, across layers, from highest score to lowest. It selects the number of pairs corresponding to the desired sharing ratio, denoted `α`. The output of that selection is the set `N`. Looking for a best earlier partner and ranking those proposals are separate steps. The search decides whom a particular head would share with. The global ranking decides which proposals enter the compressed checkpoint. Consequently, the method does not have to give each layer the same quota or restrict partners to adjacent layers or identical head positions.

In the authors’ description of the tie, the earlier head supplies the weights and the later head uses those weights for its own query, key and value projections. This is a directional decision even though the cosine comparison is symmetric. The paper motivates the choice with an observation that earlier-layer weights are more sensitive to replacement. It also reports a comparison that reverses the choice. The shared projections still receive the inputs of their respective layers. Tying therefore provides a common set of learned transformations while allowing the heads’ outputs to differ with their inputs.

The core matching equation depends only on the checkpoint matrices. The detailed procedure also mentions using 10 randomly selected Wikipedia samples for calibration and averaging the scores across them. It does not say what sample-dependent quantity enters the weight-only expression. The paper is clear about the criterion used to rank the pairs and about the lack of retraining in DirectShare. The precise role of those samples in computing the ranking is less clear. The authors call the released implementation DirectShare.

#### PostShare gives the chosen weights time to converge

PostShare uses the same rule to select head pairs. It changes when the equality between the paired matrices is imposed. DirectShare immediately replaces one collection of projections with its partner’s collection. PostShare first continues training with both collections still present. During that training it adds a penalty for a difference between corresponding matrices. The selected pairs are the targets of this extra penalty. After training, the method applies the weight sharing used by DirectShare.

```
ℒ_w = (1 / |N|) ∑_(i,j)∈N ∑_∗∈{q,k,v} ‖Wᵢ^∗ − Wⱼ^∗‖₂
```

`ℒ_w` is the loss for the weight differences. `N` is the selected set of head pairs, `|N|` is its cardinality, and `1 / |N|` is the factor that averages over those pairs. The outer `∑` goes over each ordered pair of head indices `(i,j)` in `N`, as indicated by `∈`. The inner `∑` goes through the three projection labels `q`, `k` and `v`, represented by `∗`. `Wᵢ^∗` and `Wⱼ^∗` are the corresponding matrices, `−` takes their difference, and `‖·‖₂` denotes the Euclidean norm of that difference over the matrix entries. The penalty sums the projection distances for a pair and averages the resulting costs across pairs.

```
ℒ = ℒ_post-training + γ × ℒ_w
```

`ℒ` is the objective minimized during this stage. `ℒ_post-training` denotes the ordinary post-training loss and `ℒ_w` denotes the additional weight-alignment loss. `γ` is the coefficient controlling the strength of the alignment term. The `×` sign multiplies that term by the coefficient, and `+` adds it to the ordinary loss. The two terms let the weights respond to the training data while the selected projections are encouraged to approach one another.

The logic of the penalty is local. If the paired weights become closer before substitution, the final tie makes a smaller direct change to those arrays. During full-parameter training, other parts of the network can also adjust. This gives PostShare two ways to change behavior before the tie: reducing the gap between selected projections and adapting the network through the ordinary training objective. The paper reports the result of using these together. The experiments do not separately measure their contributions to accuracy recovery.

For the reported post-training setup, the authors use English Wikipedia, LLaMA-Factory and DeepSpeed ZeRO-1. They run Adam with a learning rate of 5e-5, first momentum coefficient β₁ of 0.9 and second momentum coefficient β₂ of 0.95. The batch size is 32 for Llama2-7B and 8 for Llama2-13B, with the smaller batch attributed to available computing resources. The maximum context size is 4096, and `γ` is 0.5. The reported Llama2-7B checkpoint in the main comparison is trained for 0.5 epoch, meaning half a pass through the training corpus.

#### Measuring agreement between the two ways of choosing

The appendix compares pairs selected by weight similarity with pairs selected by map similarity. For a specified sharing ratio, the authors take the leading pairs according to each criterion. They call the resulting sets `A` and `B`. The count of matched pairs is the size of their intersection.

```
Degree = number of matched heads / number of samples
```

`Degree` is the paper’s reported measure of agreement. The numerator, `number of matched heads`, is described through `|A ∩ B|`, where the vertical bars indicate a count and `∩` means intersection. `A` holds the leading pairs from the weight-based ranking and `B` holds the leading pairs from the map-based ranking. The slash divides this count by the quantity labeled `number of samples` in the paper’s formula. The surrounding explanation does not resolve how that denominator relates to the number of pairs in each set. The reported values are best read as the authors’ agreement measure for this procedure.

For the map comparison, they use 100 randomly chosen examples per dataset to calculate average cosine similarities and repeat the process 5 times. This makes the comparison more systematic than a visual inspection of one example or one head. Its purpose is to check whether the weight rule points toward the kinds of matches that prompted the method. The downstream evaluations serve a separate purpose. They establish what happens when those matches become actual weight ties.

### Experiments and results

#### What is compared and what the scores mean

The principal experiments use the 7B and 13B versions of [Llama 2](https://md.research.elamur.ai/free/en/papers/touvron-2023-llama-2-open-foundation-fine/) and [Baichuan 2](https://md.research.elamur.ai/free/en/papers/yang-2023-baichuan-2-open-large-scale/). The evaluation runs through OpenCompass. The paper groups its headline benchmarks into reasoning, natural language understanding and knowledge-related tasks. That organization lets readers see whether a sharing rule that preserves scores in one group also preserves them in another.

In the reasoning group, CMNLI and OCNLI test Chinese natural language inference. AX-b and AX-g appear alongside RTE in the English part of the group, drawn from [SuperGLUE](https://md.research.elamur.ai/free/en/papers/wang-2019-superglue-stickier-benchmark-general-purpose/). The natural language understanding group includes reading comprehension on the middle and high portions of [RACE](https://md.research.elamur.ai/free/en/papers/lai-2017-race-large-scale-reading-comprehension/) and questions from OpenBookQA, abbreviated OBQA. CSL and TNEWS provide the paper’s content summary and content analysis tests. The knowledge-related group includes WinoGrande and [BoolQ](https://md.research.elamur.ai/free/en/papers/clark-2019-boolq-exploring-surprising-difficulty-natural/). The examination datasets C-Eval and [MMLU](https://md.research.elamur.ai/free/en/papers/hendrycks-2020-measuring-massive-multitask-language-understanding/) cover several subject areas in Chinese and English, respectively.

The main result tables compare benchmark accuracy scores for the original checkpoints and their compressed counterparts. The paper also reports some retained-performance percentages relative to a checkpoint with no sharing, and these have a different denominator. A retained-performance result describes how much of an original score or group of scores is preserved. A dataset accuracy identifies how well a system performed on a particular evaluation. Neither is the sharing ratio, which specifies the intended intervention within the module being compressed. The paper identifies subsets such as RACE-middle and RACE-high by name. It does not consistently specify a dataset split for every result.

Magnitude Pruning and LLM-Pruner are the principal compression baselines. The authors compare at matched parameter reductions and apply both pruning methods only to the multi-head attention block for these experiments. This controls which portion of the network supplies the reduction. It also makes the comparison relevant to a memory budget. The operations remain different. Pruning changes which weights are present in the compressed block, while sharing makes different positions refer to a common set of weights. The paper puts separate comparisons with a grouped-query conversion and a modified layer-wise scheme in the appendix.

#### DirectShare preserves some capabilities much better than others

In the main Llama2 results, DirectShare is tested at 10% and 30% sharing within attention. At 30%, Llama2-7B retains 99.51% of the reported average reasoning performance of the original checkpoint. Llama2-13B retains 99.21% by the same measure. An individual task can move in either direction around that near-baseline average. On Llama2-7B at the 30% target, DirectShare records 49.10 on RTE against 49.82 before sharing, and 32.50 on OCNLI against 33.12. On AX-b it records 57.07 against the original 53.53. These scores support close aggregate retention on the selected tasks. They are less informative about the behavior of individual predictions.

At the lighter sharing target, the examination scores help illustrate where DirectShare is competitive with the pruning alternatives. For Llama2-7B on MMLU, the original score is 46.69. At the 10% reduction setting, Magnitude Pruning scores 28.20, LLM-Pruner scores 38.11 and DirectShare scores 43.43. On the same checkpoint at the 30% setting, the respective compressed scores are 23.15, 25.16 and 26.53. DirectShare has the highest score among the compressed systems in both comparisons, while the original score makes clear the remaining cost at the stronger setting.

The 13B version offers another example at the 10% setting. On C-Eval, Llama2-13B starts at 40.17. The corresponding scores are 22.52 for Magnitude Pruning, 30.25 for LLM-Pruner and 37.17 for DirectShare. On MMLU, the original Llama2-13B scores 55.81. At 10%, DirectShare scores 52.81 and LLM-Pruner scores 51.45. At 30%, DirectShare scores 30.79 on MMLU and LLM-Pruner scores 27.22. The method can lead a compression comparison while giving up a substantial portion of the performance available in the original checkpoint.

Llama2-7B MMLU accuracy at the 10% attention reduction setting DirectShare keeps the highest MMLU accuracy among the compressed systems.

**The numbers**

| System or setting | accuracy % |
| --- | --- |
| Original checkpoint | 46.69 |
| Magnitude Pruning | 28.20 |
| LLM-Pruner | 38.11 |
| DirectShare (this paper) | 43.43 |

Reading comprehension makes the task dependence especially visible. At 10% sharing, the Llama2-13B RACE-middle score is 54.04 for DirectShare and 51.46 for LLM-Pruner, compared with 60.24 before compression. At 30%, DirectShare scores 26.53 on the same portion of RACE. On RACE-high, that original checkpoint scores 58.03 and its 30% DirectShare counterpart scores 27.53. Llama2-7B also loses accuracy on both parts of RACE as sharing increases. The authors report that it retains 94.23% of the base performance on the content summary and analysis tasks, illustrating how a broad category such as language understanding can contain very different responses to the same compression.

The appendix extends these comparisons to Baichuan2. On RACE-high at the 10% setting for Baichuan2-7B, DirectShare scores 48.46 against 52.63 for the original, 28.13 for Magnitude Pruning and 35.36 for LLM-Pruner. At 30%, DirectShare scores 23.44 there. For Baichuan2-13B, the original RACE-high score is 67.27, and DirectShare achieves 49.34 at 10% and 23.99 at 30%. This reproduces the broad pattern that the more aggressive sharing target can be costly for reading comprehension.

The ordering of methods can change even within a category. On BoolQ with Baichuan2-13B, the original scores 67.00. At the 30% setting, the DirectShare score is 40.83, the LLM-Pruner score is 59.42 and the Magnitude Pruning score is 50.09. In the Baichuan2 reasoning results the authors describe DirectShare as competitive with LLM-Pruner at 30%. Taken together, these findings support comparison at a particular checkpoint, resource setting and benchmark. A favorable average in one family, or a lead on a particular examination score, does not establish an ordering that carries over to the other family and tasks.

#### PostShare recovers accuracy unevenly

The main PostShare comparison uses Llama2-7B at the 30% attention-sharing target and presents accuracy after 0.5 training epoch. The suite is concentrated on areas where DirectShare had lost accuracy. The authors report that PostShare achieves 87.53% of the original overall accuracy on the reading comprehension and knowledge-related evaluation they discuss. That percentage summarizes the selected comparison. It does not describe a uniform level of recovery on each benchmark.

BoolQ shows the most conspicuous gains in the main table. Its Llama2-7B accuracy rises from 54.43 with DirectShare to 66.57 at the reported PostShare checkpoint, against 70.67 for the original. On RACE-middle it rises from 21.45 to 29.81, against 33.15 before compression. On RACE-high the corresponding compressed scores are 21.53 and 29.45, with the original at 35.51. These comparisons point to a practical reason to allow the preparatory training when an application depends on the more sensitive tasks.

Llama2-7B BoolQ accuracy with and without 30% attention sharing PostShare recovers much of the BoolQ accuracy lost with immediate sharing.

**The numbers**

| System or setting | accuracy % |
| --- | --- |
| Original checkpoint | 70.67 |
| DirectShare | 54.43 |
| PostShare after 0.5 epoch (this paper) | 66.57 |

The examination results are more mixed. On MMLU the 30% Llama2-7B result improves from 26.53 with DirectShare to 33.36 with PostShare, while the uncompressed accuracy is 46.69. On C-Eval the corresponding scores are 26.24 and 26.38, with the original at 32.20. PostShare also improves OBQA-fact from 27.60 to 33.60, compared with 42.2 before compression. The same intervention and checkpoint can therefore recover much of the BoolQ accuracy, leave the C-Eval score close to DirectShare, and put some other tasks between those outcomes.

The Llama2-13B results show gains too, with an important difference in presentation. The appendix flags the PostShare column as selecting relatively good scores across different training steps. BoolQ is reported at 71.25 with PostShare, 59.36 with DirectShare and 71.50 before sharing. On RACE-middle the figures are 32.03 for PostShare and 26.53 for DirectShare, against an original 60.24. On OBQA the reported PostShare score is 33.60, compared with 27.40 for DirectShare and 42.40 for the original. These show what was observed at favorable steps for the individual benchmarks. The 7B main result, in comparison, describes what was obtained at one stated point in training.

#### Memory savings and inference speed

The paper measures GPU memory while running BoolQ inference in OpenCompassv1.0. It reports both distinct parameter counts and memory use. For Llama2-7B, the uncompressed system has 6.74B parameters and uses 17826M of GPU memory. The 30% attention-only setting has 6.09B parameters and uses 15512M. These correspond to 90.36% of the original parameters and 87.02% of the original measured memory. The distinction between the target and these outcomes matters because attention accounts for only part of the network, and GPU memory during inference includes more than the distinct attention weights.

For Llama2-13B, the original has 13.02B parameters and uses 30800M in the same memory evaluation. The attention-only configuration has 11.76B parameters and uses 27898M. The paper reports the remaining parameter count as 90.32% of the original and the memory use as 90.58%. These results are the basis for the authors’ characterization of attention-only savings as 10-13% in their measured settings.

The paper also applies its matching idea to the feed-forward network, or FFN. This subnetwork uses its own learned projections to transform the representation at each token position. The authors compare candidate FFN weights using the gate, upward and downward projections together. Because the FFN lacks an obvious component corresponding to an attention head, they try different sizes of unit for sharing. In their search, the whole FFN layer gives the best preservation of performance among the tested units.

With a 30% target in both attention and the FFN, Llama2-7B has 4.74B parameters and uses 12932M in the BoolQ memory measurement. Llama2-13B has 9.21B parameters and uses 23002M. The reported shares of original memory are 72.55% and 74.68%, respectively. This establishes a larger memory reduction for that combined configuration. The paper’s broader accuracy comparison concerns attention sharing, and the authors discuss the narrower validation of the FFN extension separately.

Llama2-7B GPU memory during BoolQ inference in OpenCompassv1.0 Sharing both attention and feed-forward weights uses the least GPU memory in this comparison.

**The numbers**

| System or setting | M of GPU memory |
| --- | --- |
| Original checkpoint | 17,826 |
| DirectShare at 30% in attention | 15,512 |
| DirectShare at 30% in attention and FFN (this paper) | 12,932 |

For throughput, the authors use the WikiText2 test set on a single A800-80GB GPU. Llama2-7B runs at 41.70 tokens/s before compression and 8.52 tokens/s with 30% attention sharing. The configuration that also shares FFN weights runs at 8.34 tokens/s. Llama2-13B runs at 24.20 tokens/s before sharing, 5.63 tokens/s with attention sharing and 5.67 tokens/s with both modules shared. Weight reuse leaves the system with attention computations to perform at every head position. In this implementation, the measured benefit is lower memory use and comes with lower throughput.

#### Comparisons with other ways of sharing

The authors adapt a layer-wise scheme to Llama2-7B under the name SEQ. They restrict its layer sharing to the latter 60% of the stack and compare it with DirectShare at the same reported ratios. At 10%, the average across the benchmark set is 41.60 for DirectShare and 40.74 for SEQ. At 30%, it is 37.39 for DirectShare and 34.97 for SEQ. The original average is 43.71. The reported retained-performance figures at 30% are 85.54% for DirectShare and 80.00% for SEQ.

The individual scores help specify what the average means. At 30%, SEQ scores 22.63 on RACE-middle while DirectShare scores 21.45. On BoolQ at that ratio, DirectShare scores 54.43 and SEQ scores 52.60. On MMLU the scores are 26.53 and 23.49, respectively. The aggregate favors the head-wise approach in this comparison, although an individual dataset can favor the layer-wise one. The experiment tests this adaptation of SEQ and its particular range of eligible layers.

The appendix also converts Llama2-7B to [grouped-query attention](https://md.research.elamur.ai/free/en/papers/ainslie-2023-gqa-training-generalized-multi-query/) using neighboring groups of size 2. The reported average is 32.42 for that conversion, compared with 41.60 for DirectShare at 10% and 37.39 for DirectShare at 30%. On BoolQ the converted grouped-query system scores 37.83, compared with 67.74 and 54.43 for those DirectShare settings. On AX-b, however, the grouped-query score of 58.33 is above the DirectShare scores of 54.17 and 57.07. The comparison shows how those specific conversions perform on the same benchmarks. The grouping structure offers a different way to choose a reduction, so the three configurations should be read with their settings attached.

### What the ablations show

#### Choosing the partner and choosing what to tie

The main matching ablation uses Baichuan2-7B and compares rules on [PIQA](https://md.research.elamur.ai/free/en/papers/bisk-2019-piqa-reasoning-about-physical-commonsense/) and OpenBookQA. The authors try using each of the query, key and value matrices alone to score a joint match. They also compare the query–key rule with concatenating all three matrices, and with separately matching each projection type. These comparisons test both the information that goes into a match and whether the chosen partner is the same across projections.

At the 5% sharing setting, the query–key rule scores 75.84 on PIQA. The query-only, key-only and value-only rules each score 74.92. Scoring with all three concatenated matrices yields 74.59, and matching the three projections independently yields 71.71. On OpenBookQA at that setting, the query–key rule scores 33.9 and the rule that scores all three jointly reaches 34.7. The separately matched projections score 27.6. The matching rule selected by the authors offers a favorable pattern across the comparisons, and the OpenBookQA case shows that a different joint score can lead at an individual operating point.

The most revealing comparison is between using a common partner and choosing each projection’s source independently. Query and key work together to score positions. Value then determines what the head gathers from them. Independently selected matrices may each have a close counterpart for the corresponding projection while coming from different learned combinations. The inferior results for separate matching support preserving the set of projections as a unit. The experiments evaluate the resulting system behavior, so they do not identify which particular mismatch between the three matrices produced each drop.

The map-versus-weight analysis tests an earlier part of the argument. For Llama2-7B, the appendix reports a degree of agreement of 100% on WMT-14, 91.30% on CommonsenseQA and 100% on WSC. The reported average is 97.10%. Alongside the visualization of highly similar head pairs, these values support using the query–key weights as a proxy for finding strongly similar attention-map pairs in these settings. The downstream matching ablation gives a second kind of support because it judges the effect of actually tying the chosen weights. Agreement in rankings addresses which pairs look promising. Benchmark accuracy addresses how the network behaves after it commits to them.

#### Which side of the tie supplies the weights?

The authors compare keeping the earlier head’s values with keeping the later head’s values for matched pairs. The reported overall averages are 37.25 for keeping the earlier head and 37.18 for keeping the later one. The outcome varies by benchmark. Keeping the earlier values yields 20.22 on TNEWS against 12.20 for keeping the later values. On BoolQ the earlier choice yields 54.43 and the later choice yields 57.22. On RACE-middle those choices score 21.45 and 25.00, respectively.

The small difference between the aggregate results provides modest support for the actual direction used by the algorithm. The authors favor it because of their observations about sensitivity in the earlier layers. The per-task reversals show why the direction should be regarded as an empirical design choice. Even with the membership of each pair fixed, deciding which weights survive can change downstream behavior.

The visualizations of where sharing occurs address a different property of the selection. The figures cover the Llama2 and Baichuan2 checkpoints at the sizes used in the main study. The authors observe that the distribution of shared heads across layers looks similar as the sharing ratio changes and that the ties are relatively spread across the attention layers compared with sharing whole layers. The algorithm imposes a common ranking without a separate budget for each layer. The resulting distribution is therefore a property of the selected matches. The visualization alone gives no estimate of what would happen if a different distribution were imposed at the same budget.

#### How long to post-train

The PostShare training curves show that more alignment time can help one task while yielding a lower score on another. On Llama2-7B, BoolQ accuracy is 68.29 at 0.30 epoch, 66.57 at 0.50 and 65.38 at 1.00. For RACE-middle it is 28.48 at 0.30, 29.81 at 0.50 and 30.43 at 0.70. WinoGrande scores 52.98 at 0.50 and 55.09 at 0.80, followed by 54.39 at 0.90. The differences in timing explain why a checkpoint picked for one benchmark can give up performance available at another point in the same run.

The authors attribute these patterns to possible overfitting with a limited, domain-constrained corpus. For Llama2-13B, they report that a relatively small number of training steps can suffice and describe selecting an appropriate duration as harder at the larger size. These observations concern the joint training recipe. Because ordinary continued training and alignment occur together, the curves measure both effects and do not isolate a cause for the declines. What the curves directly show is that benchmark trajectories differ and that some peak before the end of the training run.

The time comparison helps put the cost in perspective. For Llama2-7B on English Wikipedia, the authors report around 11.27 hours for the 0.5 epoch PostShare run and 10.78 hours for ordinary full-parameter post-training in the same settings. The paper characterizes the gap as roughly 30min. The extra term adds relatively little time to the measured training run. Choosing PostShare instead of immediate tying still entails that continued training, with its associated compute and checkpoint choice.

The authors also try a route that combines DirectShare and PostShare. At 30% sharing with 0.5 epoch of training on Llama2-7B, the combination performs on par with PostShare in their comparison and does better on some benchmarks, including BoolQ and WinoGrande. They suggest it might mitigate overfitting in those cases. The figure supports the performance comparison for that setup. The proposed explanation remains a hypothesis because the experiment does not separately vary the factors that could account for the effect.

#### How sharing interacts with size and precision

The paper checks whether head-wise sharing remains usable below the sizes used in the main study. It names BERT-base and GPT2-small in the discussion of smaller systems and gives detailed translation scores for GPT2-small. The WMT-14 English–French comparison sweeps the sharing ratio from 0% to 50% in steps of 10%. The reported [BLEU score](https://md.research.elamur.ai/free/en/concepts/bleu/) is 43.62 at 0%, 41.34 at 30% and 39.44 at 50%. METEOR is 42.33 at 0% and 36.62 at 50%. The reported trajectory indicates a deterioration as more weights are shared while retaining measurable translation performance at the strongest setting tested.

There is an ambiguity about the procedure used for that sweep. The body says the GPT2-small result at 50% is obtained without post-training, whereas the table caption labels the experiment PostShare. The numerical comparison across ratios is explicit. The training status of the sweep cannot be assigned confidently to one variant from those descriptions. The smaller-system evidence is also drawn from a translation setting, whereas much of the large-system comparison concerns reasoning, comprehension and knowledge. This makes it evidence for applicability to another setup, with limited scope for direct comparisons of size.

Quantization gives the authors a way to test whether sharing can be combined with a method that targets the precision of the stored weights. They apply GPTQ at 4 bit precision after 30% DirectShare on Llama2-7B. BoolQ goes from 54.43 with sharing alone to 51.95 with the combination. C-Eval goes from 26.24 to 21.88, and MMLU goes from 26.53 to 25.38. CMNLI moves in the other direction, from 33.33 to 34.61. The authors describe the additional performance drop as no more than 5 points across this comparison. The result shows that the two operations can be used in sequence with the reported accuracy costs. The experiment reports benchmark scores for the combination, leaving its actual memory use unquantified there.

### Limitations

#### Limits the authors state

The first explicit limit concerns the feed-forward extension. The paper’s main method is motivated by attention-map similarity and evaluated most fully on the attention block. Although it reports memory measurements for joint attention and FFN sharing on Llama2, the authors say their downstream evaluation of FFN sharing was completed only on Baichuan2-7B. They identify comparisons across more checkpoints and against baselines as future work. The combined configuration’s memory figures therefore come with a narrower basis for judging its impact on capabilities.

The authors also state that available computing resources restricted their large-system experiments to sizes up to 13B. They hypothesize that additional redundancy could make head-wise sharing suitable for larger systems. Their measurements establish behavior for the sizes tested. The smaller translation experiment shows another setting in which the approach can be applied, subject to the ambiguity about training, and supplies no direct evidence about behavior beyond the upper size limit.

A further limitation appears in the discussion of post-training. The authors use a limited English Wikipedia corpus and observe that accuracy can fall after it reaches a peak on a particular benchmark. They identify overfitting as a risk, with the issue more apparent in their discussion of Llama2-13B. Their latency discussion also describes the current difficulty of saving memory and maintaining speed at the same time. The measured throughput on WikiText2 makes that implementation limitation material to deployment.

#### What the experimental setup leaves open

Weight similarity is a practical ranking criterion, with corroboration from map similarity, but the two quantities answer different questions. Cosine similarity measures alignment in direction and does not specify the absolute change made by substituting one set of weights for another. The map comparison measures behavior on sampled inputs. Downstream accuracy depends on the entire network, including the value projections and all operations that receive the head’s output. A highly ranked pair can be a plausible candidate while the cost of tying many such pairs together still varies by task.

The criterion also contains a structural restriction. Each later head can propose an earlier partner, and the top candidates are picked by a shared ranking. The paper tests the outcome of that rule and includes a comparison for which head supplies the retained weights. It does not establish that independently picking the highest-scoring earlier partner for each head yields the best possible collection of ties for a fixed memory budget. A set of ties can have joint consequences even if each looks attractive by itself. The description also gives limited detail on resolving dependencies when selected pairs share heads or form chains, which matters for reproducing the exact weights retained by the rule.

The comparison with pruning controls the scope of the changed module and aims to match the number of reduced parameters. Those choices make the results interpretable as a compression comparison. They leave open how the methods would rank under a budget expressed in end-to-end latency, measured memory on another system or the amount of post-training available. The grouped-query and layer-wise comparisons are similarly specific. One uses a neighboring grouping with the reported size, and the other adapts a layer-wise method to a specified portion of the stack. The results establish the ordering of those configurations in the paper’s evaluations.

The PostShare results support accuracy recovery for several benchmarks, with differing amounts of recovery across tasks. The appendix times ordinary continued training and the alignment run, but this is a timing comparison. It does not establish how much of the observed accuracy recovery is attributable to the regularizer on its own. A comparison of otherwise equivalent training runs followed by the same tie would help distinguish alignment from the effects of continuing training on Wikipedia. The Llama2-13B results selected across different steps also leave open the performance of a single checkpoint chosen for the full suite by one common rule.

Finally, the aggregate accuracy scores and qualitative generation examples describe different kinds of evidence. Near-original average accuracy on the selected reasoning benchmarks does not identify which individual decisions are preserved. The generation examples show that compressed systems can produce continuations and translations, but the examples do not quantify their reliability on open-ended inputs. The paper establishes a memory–accuracy tradeoff for the tested checkpoints and benchmarks, together with the throughput of its implementation on the stated GPU. Results for a specific device or application would depend on the corresponding workload and on which part of that tradeoff matters there.

### What came after

No later works are documented here. The paper leaves larger checkpoints, broader validation of feed-forward sharing and faster inference with shared weights as open directions.

## Cite

Cite as Zouying Cao, Yifei Yang and Hai Zhao. 2024. Head-wise Shareable Attention for Large Language Models. Findings of the Association for Computational Linguistics: EMNLP 2024.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.18653/v1/2024.findings-emnlp.144](https://doi.org/10.18653/v1/2024.findings-emnlp.144)

```bibtex
@inproceedings{cao2024head,
  title = {{Head-wise Shareable Attention for Large Language Models}},
  author = {Zouying Cao, Yifei Yang and Hai Zhao},
  booktitle = {Findings of the Association for Computational Linguistics: EMNLP 2024},
  year = {2024},
  doi = {10.18653/v1/2024.findings-emnlp.144},
  url = {https://doi.org/10.18653/v1/2024.findings-emnlp.144}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
