---
title: "CHAI: Clustered Head Attention for Efficient LLM Inference (2024)"
description: "CHAI groups attention heads that behave alike to cut inference work and key-cache memory, with no retraining and measured accuracy trade-offs."
canonical: "https://research.elamur.ai/free/en/papers/agarwal-2024-chai-clustered-head-attention-efficient/"
---
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/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/agarwal-2024-chai-clustered-head-attention-efficient/)

[home](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/) / CHAI: Clustered Head Attention for Efficient LLM Inference

# CHAI: Clustered Head Attention for Efficient LLM Inference

Paper · 2024 · Saurabh Agarwal, Bilge Acun, Basil Hosmer et al.

**Authors:** [Saurabh Agarwal](https://md.research.elamur.ai/free/en/authors/saurabh-agarwal/), [Bilge Acun](https://md.research.elamur.ai/free/en/authors/bilge-acun/), [Basil Hosmer](https://md.research.elamur.ai/free/en/authors/basil-hosmer/), [Mostafa Elhoushi](https://md.research.elamur.ai/free/en/authors/mostafa-elhoushi/), [Yejin Lee](https://md.research.elamur.ai/free/en/authors/yejin-lee/), [Shivaram Venkataraman](https://md.research.elamur.ai/free/en/authors/shivaram-venkataraman/), [Dimitris Papailiopoulos](https://md.research.elamur.ai/free/en/authors/dimitris-papailiopoulos/) and [Carole-Jean Wu](https://md.research.elamur.ai/free/en/authors/carole-jean-wu/) · **Year:** 2024 · **Venue:** arXiv:2403.08058 · **Licence:** [arXiv — non-exclusive license to distribute](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

[licence](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

- [PDF](https://arxiv.org/pdf/2403.08058)
- [arXiv 2403.08058](https://arxiv.org/abs/2403.08058)

## What it is about

CHAI groups attention heads that behave alike to cut inference work and key-cache memory, with no retraining and measured accuracy trade-offs. · about 34 minutes to read

**In this deep dive**

1. [Summary](#dd-summary)
2. [Ideas worth borrowing](#dd-ideas-worth-borrowing)
3. [How Mova uses it](#dd-how-mova-uses-it)
4. [The problem and its context](#dd-the-problem-and-its-context)
5. [The method, step by step](#dd-the-method-step-by-step)
6. [Experiments and results](#dd-experiments-and-results)
7. [What the ablations show](#dd-what-the-ablations-show)
8. [Limitations](#dd-limitations)
9. [What came after](#dd-what-came-after)

### Summary

Generating text with a large [language model](https://md.research.elamur.ai/free/en/concepts/language-model/) requires more than storing its learned parameters. As a sequence grows, the system also keeps intermediate information about earlier tokens so that it can continue without processing the entire history again. Attention heads repeatedly consult this history, creating both computational work and memory traffic. CHAI, short for Clustered Head Attention, asks whether all those heads need to calculate their own attention scores. Its central observation is that several heads often assign very similar weights to the same tokens. Rather than treating each head as an independent computation, CHAI groups heads with similar behavior and shares an attention calculation within each group.

The important distinction is between sharing attention weights and removing everything a head contributes. CHAI reduces the query and key computations associated with redundant heads, but preserves their value vectors. Queries and keys determine how strongly a head attends to different positions; values carry the information combined using those weights. The authors find that similar attention patterns do not justify replacing all of these components together. Their method therefore keeps the different value representations while avoiding repeated calculations of nearly the same weighting pattern. This makes CHAI an approximate inference method for an already trained network, instead of a new architecture that must be learned from scratch.

CHAI separates its decisions into an offline stage and a request-specific stage. For each network, the authors examine attention behavior on 1024 samples from C4 and choose a cluster count separately for each layer. They then leave those counts unchanged across evaluation datasets. For a new request, ordinary multi-head attention runs while the system observes the first five tokens. K-Means clustering uses those observations to decide which heads belong together. The memberships then remain fixed for the rest of that request. This arrangement reflects two findings: the amount of redundancy differs across layers, and the identities of redundant heads depend on the input. Later layers generally show more correlation, while a brief observation period frequently suffices to identify useful groupings.

The experiments cover OPT-66B, LLaMA-7B, and LLaMA-33B, using five evaluation datasets. The headline results are a reduction of up to 21.4% in key-and-value cache memory and an inference speedup of up to 1.73×, without fine-tuning. Those benefits come with changes in accuracy, rather than exact preservation of the original outputs. The detailed tables generally favor request-specific clustering over a fixed grouping, and show substantially smaller accuracy losses than aggressive head pruning on the LLaMA networks. Some numerical claims in the prose conflict with the tables: the abstract gives a maximum accuracy deviation of 3.2%, whereas the evaluation discussion states different maxima that do not consistently match its own entries. Latency reporting also varies between the discussion and figure captions. The strongest supported conclusion is consequently specific: attention-score redundancy can be exploited after training to save computation and key-cache storage, and preserving distinct values is important to the observed quality.

### Ideas worth borrowing

Share repeated behavior. Components can remain individually active while performing nearly identical work. CHAI looks for similarity in their observable attention patterns, rather than assuming that useful components must always execute separately. This principle applies to ensembles, repeated database operations, symbolic analyses, and other systems where several paths may reach equivalent intermediate results. The useful question is whether work can be shared without discarding distinctions needed later.

Separate stable structure from contextual membership. The method chooses how many groups a layer needs offline, but decides which heads enter those groups for each request. This divides a costly adaptation problem into a relatively stable structural decision and a cheaper contextual decision. Similar arrangements can help query planning, specialist routing, or document processing when the overall processing budget changes slowly but the useful combination of workers depends on the current input.

Observe briefly, then reuse the decision. CHAI pays for full computation during an initial observation period and amortizes the resulting grouping over subsequent decoding. This works because the authors observe relatively little membership change after their selected warm-up. The transferable idea is to measure whether an early signal predicts later behavior well enough to support a cheaper continuation. It is especially relevant to repeated operations within a single task, where adaptation at every step could consume the savings it creates.

Share selection without erasing content. CHAI preserves value vectors even when it shares the attention calculation that selects among them. Its value-sharing comparison shows why this boundary matters. More broadly, two processes may agree about which evidence deserves attention while retaining different representations of that evidence. Retrieval, document analysis, and reasoning systems can potentially share a selection stage without collapsing the separate information consumed afterward.

Allocate approximation locally. The authors do not impose a uniform grouping across every layer. Their observations show that early and late layers differ in redundancy, so the approximation budget follows local behavior. This is useful wherever a pipeline contains stages with different sensitivity or repetition. A global compression setting may waste opportunities in tolerant stages while damaging stages that preserve important distinctions.

Evaluate quality, work, and state separately. CHAI is assessed through task accuracy, latency, and cache storage. These measurements answer different questions: whether the output remains useful, whether execution becomes faster, and whether persistent intermediate state becomes smaller. The same separation helps evaluate parsers, graph processors, and data pipelines. Fewer operations alone do not establish a practical speedup, and a smaller cache does not establish an acceptable answer.

### How Mova uses it

Mova is a small, transparent language system written in Rust. Its native CPU language path uses explicit linguistic structure and learned perceptron parameters; the separate GPU parser uses a transformer. CHAI therefore has a possible direct connection to GPU attention, but many of its more useful lessons concern how to organize repeated work, preserve evidence, and evaluate approximations. The status marks below are proposals based on documented mechanisms. They do not establish that CHAI has been implemented in Mova, and an apparently new proposal may overlap work outside the documented scope.

Idea: Share repeated observable behavior. Where: Section 3.1 and Figures 6–7. Area: execution and data processing. Mova: частково є (the mouse team shares a document parse and retained graph in `world/src/knowledge/retention/mice.rs`). CHAI suggests inspecting whether different mouse profiles repeatedly derive the same intermediate observations and could reuse a cached result. Shared input already exists; sharing additional derived work would need a separate design. Why Mova: reducing duplicate computation could let bounded reading spend more effort on observations that actually differ.

Idea: Separate structural capacity from contextual assignment. Where: Sections 3.2–3.3 and Figure 10. Area: operational planning. Mova: частково є (`layers` provides a domain registry and explicit routing, while worker capabilities are configured). A proposed extension could distinguish a stable set of processing slots from the specialists assigned to those slots for a particular document. This would transfer CHAI’s division of responsibilities, without treating its head-clustering result as proof that Mova’s routing will benefit. Why Mova: stable interfaces could coexist with task-sensitive allocation of limited resources.

Idea: Use an initial observation period before committing resources. Where: Section 3.3 and Figure 9. Area: bounded execution. Mova: нове (a CHAI-style warm-up decision for subsequent native processing is not established by the documented mechanisms). Mova could inspect an initial document segment before choosing which expensive analyses to continue. The observation window would need its own evidence; CHAI’s five-token choice concerns autoregressive attention and should not become an arbitrary Mova constant. Why Mova: a measured early decision could reduce repeated routing work during longer reading tasks.

Idea: Preserve distinct content when sharing selection. Where: Section 4.5 and Table 4. Area: knowledge representation. Mova: частково є (frames, world state, source provenance, and dictionary credits have separate roles). If several readers select the same passage, Mova could share retrieval while retaining each reader’s extracted roles, uncertainties, and source-bound conclusions. Identical passage selection would not justify merging the resulting claims. Why Mova: this could save retrieval work while preserving distinctions needed for explanation and contradiction handling.

Idea: Choose approximation budgets independently for different stages. Where: Sections 3.1–3.2 and Figure 8. Area: execution and evaluation. Mova: частково є (`docs/gpu-exec.md` distinguishes exact stages from measured approximants). A further application would measure which stages tolerate more aggressive reuse and which require independent execution. No CHAI-derived setting is established for Mova’s parser or readers. Why Mova: local decisions could improve efficiency without applying one approximation policy to components with different error costs.

Idea: Measure quality, latency, and stored state independently. Where: Sections 4.2–4.4. Area: evaluation. Mova: вже є (`tools/dictindex` reports stored bytes, timing conditions, indexed scope, and repeated-result hashes; GPU execution also separates agreement from performance). CHAI reinforces the need to keep these dimensions visible when introducing shared computations. A smaller representation should still be checked for answer quality and real execution cost. Why Mova: separate measurements make it possible to identify useful savings without mistaking a storage improvement for better understanding.

Idea: Examine attention redundancy in the GPU parser. Where: Section 3.1 and Figures 2, 6, and 7. Area: GPU parsing. Mova: нове (CHAI-specific attention profiling in `gparse` is not documented). The GPU parser could be profiled for correlated attention patterns before any implementation is considered. Its transformer parsing task differs from the decoder-only generation setting studied by CHAI, so the existence and usefulness of redundancy remain unknown. Why Mova: profiling could reveal whether there is a real optimization opportunity before engineering effort is committed.

Idea: Treat output similarity as weaker than equivalence. Where: the approximate clustering formulation in Section 3.1. Area: mathematical modeling. Mova: вже є (`docs/groupants.md` and the correspondence tooling distinguish declared observations from proof of source equivalence). A cluster of similar native observations could support an approximant, but should not authorize replacing logical rules as though they were identical. Why Mova: explicit conformance boundaries fit its requirement that evidence explain what a comparison establishes.

Idea: Keep cluster-level reuse separate from evidence identity. Where: Section 3.4 and Figure 3. Area: provenance. Mova: частково є (`tools/dictindex` preserves posting identities, source credits, and sentence evidence). Shared computation could retain separate references to every contributing source rather than treating similar examples as one source. CHAI’s preservation of values offers an architectural analogy, not a licensing or provenance result. Why Mova: reuse should reduce work without concealing which source supports each conclusion.

Idea: Use a fixed calibration source across downstream evaluations. Where: Section 3.2 and the statement that cluster counts are unchanged for new datasets. Area: evaluation design. Mova: частково є (held-out gates and teacher-separated assessments are documented). An optimization profile could be selected on an admitted development corpus and frozen before evaluation on other tasks. Why Mova: this would help distinguish a generally useful execution policy from one adjusted to the assessment being reported.

Idea: Compare contextual selection against a fixed alternative. Where: Section 3.3 and Tables 1–3. Area: evaluation. Mova: нове (a direct static-versus-contextual comparison for shared native observations is not established). Any adaptive reuse mechanism could be compared with a fixed grouping using the same component budget. This would test whether contextual adaptation provides value beyond the underlying reduction in work. Why Mova: the extra machinery should earn its cost through measured gains.

Idea: Include an uninformed grouping control. Where: Figure 1 and Appendix Figure 14. Area: evaluation controls. Mova: частково є (school reports and development gates include negative controls). For a proposed observation-sharing mechanism, an uninformed grouping could test whether the chosen similarity measure matters. Such a control would be kept outside ordinary deterministic production execution. Why Mova: it could expose an elaborate grouping rule that performs no better than an arbitrary allocation.

Idea: Evaluate the component boundary being removed. Where: Section 4.5, the QKV comparison. Area: ablation design. Mova: частково є (rule and parameter changes pass explicit regression gates). Before combining analyses, Mova could test sharing only retrieval, then sharing intermediate extraction, and finally sharing conclusions as distinct interventions. These are proposed experiments, not equivalent operations. Why Mova: they would identify which part of a computation is safely reusable and which carries essential information.

Idea: Distinguish uninformative behavior from redundant behavior. Where: Section 2 and Figure 4. Area: analysis and statistics. Mova: нове (a general diagnostic separating these cases across native specialists is not documented). A reader can produce a sharply focused, useful observation that another reader also produces. Such duplication differs from a reader contributing no discriminative evidence. Why Mova: the distinction could support sharing useful work rather than removing components merely because they agree.

Idea: Verify whether early assignments remain valid. Where: Section 3.3 and Figure 9. Area: sequential evaluation. Mova: нове (persistence measurements for warm-up-based native assignments are not established). If Mova adopts an early routing decision, it should record when later document material would have changed that decision. The CHAI study motivates the measurement but supplies no guarantee for narrative topic changes. Why Mova: this could reveal when a cheap fixed continuation misses a newly relevant specialist.

Idea: Include adaptation overhead in whole-request measurements. Where: Section 4.4. Area: performance evaluation. Mova: частково є (`tools/twin` records predicted and measured costs, and dictionary measurements identify excluded startup costs). Proposed adaptive execution should report the time spent observing, selecting, and preparing shared state alongside subsequent savings. Why Mova: an optimization is useful only when the saved work outweighs the work required to enable it.

Idea: Prefer executable savings over abstract sparsity. Where: Section 2 and the latency discussion in Section 4.4. Area: systems engineering. Mova: частково є (the architecture favors compiled tables, integer comparisons, and explicit Rust execution). A reuse mechanism should remove actual operations or memory reads in the chosen implementation, rather than only marking logical work as unnecessary. Why Mova: the benefit must survive the cost of dispatch, indexing, and coordination.

Idea: Preserve the exact reference implementation. Where: comparisons with unmodified multi-head attention throughout Section 4. Area: regression evaluation. Mova: вже є (CPU-only execution is the reference, with GPU approximants measured against it). Any CHAI-inspired change should remain separately identifiable and comparable with the established path. Why Mova: a stable reference supports diagnosis when performance improves but output agreement changes.

Idea: Report heterogeneous effects instead of only a headline maximum. Where: Tables 1–3 and Section 4.4. Area: evaluation reporting. Mova: вже є (documented school traces, parser diagnostics, and scoped dictionary measurements retain detailed outcomes). Proposed reuse should be reported by task and relevant input conditions, including regressions. Why Mova: a favorable maximum can conceal the particular constructions or reasoning tasks that become less reliable.

Idea: Investigate skewed workloads before balancing them. Where: Section 4.5 and Figure 13. Area: scheduling. Mova: нове (CHAI-style cluster-size analysis of mouse observations is not documented). If many native profiles share a common observation while a few remain distinctive, their useful grouping may be highly uneven. Equal-sized groups should not be assumed to reflect the work. Why Mova: recognizing skew could improve caching and scheduling while preserving uncommon but important analyses.

Idea: Keep computational shortcuts separate from learning. Where: Sections 3.4–3.5, where clustering changes inference without fine-tuning. Area: architecture. Mova: вже є (`docs/hybrid-system.md` separates execution receipts, reviewed graph knowledge, and parameter training). Reusing an intermediate result should not automatically revise a dictionary entry or admit a rule. Why Mova: a successful shortcut is evidence about execution, not evidence that new knowledge has been learned.

Idea: Require separate evidence for combined optimizations. Where: Section 2, the discussion of quantization. Area: experimental design. Mova: частково є (groupants and approximation tooling require declared compatibility and evidence). Combining compressed storage, GPU execution, and shared observations would need joint measurements rather than assumed cumulative benefits. Why Mova: interacting shortcuts can change both error behavior and execution cost.

### The problem and its context

#### Attention makes inference expensive in several ways

The paper concerns [efficient inference](https://md.research.elamur.ai/free/en/topics/efficient-models/): executing an already trained system with fewer resources while retaining useful output quality. Its starting point is the cost of attention in large decoder-only transformers. The authors describe attention as a substantial contributor to both computation and memory requirements, potentially accounting for over 50% of those demands. A request can require several GPUs, making intermediate state a practical serving constraint instead of a minor implementation detail.

A [transformer](https://md.research.elamur.ai/free/en/concepts/transformer/) processes representations through repeated blocks. In the decoder-only setting described by the authors, each block contains self-attention and an MLP, a learned transformation applied alongside attention. The attention mechanism allows the current position to use information associated with earlier positions. Multi-head attention performs this operation through several separately parameterized heads, allowing different weighting patterns over the same sequence.

The number of heads can grow with network size. The paper contrasts 32 heads per layer in LLaMA-7B with 64 in LLaMA-65B. More heads mean more individual attention operations and more associated intermediate state. CHAI targets repetition within this structure. Its premise is not that multi-head attention is unnecessary, but that its trained heads do not always produce sufficiently different attention patterns to justify fully separate execution.

Autoregressive generation adds a second consideration. Once earlier tokens have been processed, their keys and values are retained in a cache. Subsequent decoding can consult that cache rather than reconstructing those representations. This saves repeated computation, but the stored history expands as the sequence becomes longer. A method that reduces attention arithmetic without shrinking the retained state addresses only part of the problem.

#### Why earlier pruning was an incomplete answer

The authors place CHAI among methods that reduce the work done by an existing network. They distinguish this from knowledge distillation, architectural search, hardware-oriented optimization, and quantization. Those other approaches form the broader context of efficient transformers, but CHAI’s particular question is whether trained attention can be executed more economically through runtime grouping.

Classical pruning removes weights or structural components judged unnecessary. The paper describes a practical difficulty: identifying removable components may involve iterative gradients, repeated training, or fine-tuning. At the scale considered here, those procedures create substantial resource demands of their own. A method can therefore be attractive in principle while remaining expensive to adapt to an already deployed network.

Another difficulty concerns execution hardware. Sparse weights do not automatically produce a proportionate reduction in runtime. The authors note that contemporary GPUs may not efficiently support the particular sparse operations created by a pruning method. Structured changes, such as removing heads or layers, offer another route, but earlier approaches of that kind can still depend on costly optimization or retraining.

The cited work on [specialized attention heads and pruning](https://md.research.elamur.ai/free/en/papers/voita-2019-analyzing-multi-head-self-attention/) belongs to this history. CHAI changes the immediate criterion. Rather than treating every retained head as independently necessary and every removed head as individually unimportant, it looks for groups whose attention scores overlap. A useful head can be redundant with another useful head.

#### The contrast with contextual sparsity

DejaVu provides the paper’s main runtime-pruning comparison. As characterized by the authors, it identifies components that are unneeded for a particular context. For attention, the relevant signal is a head assigning roughly uniform weights across tokens. Such behavior suggests that the head is not sharply selecting among positions.

The CHAI authors inspect this signal in OPT-66B and LLaMA-7B. Their illustrative plots show uniform-looking heads in OPT-66B, while the LLaMA example contains heads with focused attention. The distinction matters because a method based on removing uniform heads may find fewer safe opportunities in the latter setting.

Yet focused attention can still be repeated. Several LLaMA heads may concentrate on the same position. CHAI’s proposed opportunity survives even when the uniform-attention opportunity does not. The paper suggests that differences in training duration and data could help explain the contrast between OPT and LLaMA, but does not establish that explanation through a controlled training experiment.

#### Sharing by design versus sharing after training

Another line of work changes attention architecture so that components are shared from the outset. The authors discuss multi-query attention and [grouped-query attention](https://md.research.elamur.ai/free/en/papers/ainslie-2023-gqa-training-generalized-multi-query/) as examples. Their concern is the cost of adapting existing systems: sharing built into an architecture can require additional training, and the resulting quality tradeoff may not be known beforehand.

The paper connects this discussion to [LLaMA 2](https://md.research.elamur.ai/free/en/papers/touvron-2023-llama-2-open-foundation-fine/), describing training from scratch as a route used to obtain grouped-query benefits. CHAI instead searches for sharing opportunities in trained behavior. Its calibration phase inspects activations but does not update the learned weights.

The authors also distinguish their proposal from cache-compression methods that retain selected tokens. In their account, those methods can reduce storage after the full transformer calculation has occurred. CHAI aims to avoid some of the computation itself as well as remove redundant cached keys.

Speculative decoding provides a further contrast. It uses a cheaper draft generator whose proposed sequence is checked by a target system. The authors acknowledge its latency benefits but emphasize the additional resources needed to maintain both participants. CHAI’s focus is on reducing the resources used within the attention computation of the target itself.

### The method, step by step

#### Start with what each attention head computes

The paper’s notation describes an input sequence using a matrix x. Its rows correspond to token positions, and its columns hold the representation of each position. Each attention head applies separate learned projections to create keys, queries, and values.

```
Kʰ = xW_Kʰ
```

Kʰ is the key representation for head h. The superscript identifies the head rather than a power. The matrix x contains the input representations, and W_Kʰ is that head’s learned key-projection matrix. Keys provide the representations against which queries are compared.

```
Qʰ = xW_Qʰ
```

Qʰ is the query representation for head h, and W_Qʰ is its learned query-projection matrix. A query determines what the head is looking for when it weights positions in the sequence. The same input x can yield different queries because the projection differs across heads.

```
Vʰ = xW_Vʰ
```

Vʰ is the value representation for head h, with W_Vʰ its learned value-projection matrix. Values are the content combined after the attention weights have been calculated. This separation between weighting and content becomes central to CHAI.

The paper gives the attention calculation in the following form.

```
Aʰ = σ((Qʰ(Kʰ)ᵀ) / √d)
```

Aʰ is the attention-weight matrix for head h. The multiplication compares queries with keys, and the superscript T denotes transposition. The function σ is softmax, which converts the scores into normalized weights. The paper introduces d as the representation dimension and uses it in the scaling term. The notation here follows that presentation instead of supplying an unstated alternative dimensional convention.

The output of multi-head attention combines the separate weighted-value results.

```
y = ⊕ₕ AʰVʰ
```

The symbol y denotes the combined output, and ⊕ means concatenation across the heads. Each term AʰVʰ applies one head’s attention weights to that head’s values. The expression condenses the paper’s expanded concatenation without relying on its inconsistent endpoint indexing.

This formulation reveals the sharing opportunity. If several Aʰ matrices are sufficiently similar, separately calculating every one of them may be avoidable. It does not follow that their Vʰ matrices are also interchangeable. CHAI shares the attention calculation while retaining the distinct values that those weights combine.

#### Define similarity at the operation that will be shared

The authors formulate their task as grouping query–key pairs according to the attention behavior they produce. In the clustering discussion they use a simplified attention function.

```
f(Q, K) = σ(QKᵀ)
```

The function f maps a query representation Q and key representation K to attention weights. The scaling term from the earlier attention expression is omitted in this formulation, as it is in the paper. The purpose is to express similarity of the operation’s output, rather than to claim that the parameter matrices themselves must be alike.

Let S collect the query–key pairs associated with all attention heads in a layer. The method seeks subsets Sᵢ that cover that collection.

```
⋃ᵢ₌₁ᵏ Sᵢ = S
```

Here k is the number of clusters, Sᵢ is the collection of head pairs assigned to cluster i, and the union symbol means that every head pair is included somewhere in the grouping. Operationally, K-Means supplies assignments to clusters. The paper’s set formulation expresses coverage more directly than it specifies every implementation detail.

The intended within-cluster relationship is approximate agreement.

```
f(Qⁿ, Kⁿ) ≈ f(Qᵐ, Kᵐ)
```

The superscripts n and m identify heads assigned to the same group. The approximation sign expresses the desired similarity of their attention outputs. It does not establish exact equality or provide a bound on the eventual change in task accuracy.

The presentation contains notation slips, including a value symbol appearing where the surrounding discussion calls for a query–key pair. The consistent operational description is clear nevertheless: group heads whose queries and keys produce similar attention patterns, then avoid recalculating those patterns independently.

#### Establish that the opportunity exists

Before designing the runtime procedure, the authors inspect attention correlations. For LLaMA-7B, they examine both a single example and averages over 1024 C4 samples. The average view shows how redundancy varies through the network; the individual view shows that a particular request can have its own grouping.

An illustrative layer contains clusters whose internal correlation exceeds 0.95. This is evidence of strong similarity for that observation, not a universal threshold specified for every grouping decision. The broader plots show that later layers tend to contain more correlated heads than early layers.

This layer dependence rules out a simple assumption that the same cluster count should work everywhere. An early layer with diverse weighting patterns may need many representatives. A later layer with repeated patterns may permit substantially more sharing. CHAI therefore calibrates the capacity of each layer separately.

The distinction between average and individual correlations also rules out treating a single offline assignment as sufficient. Heads that appear related across a collection of examples may not be the best group for every particular prompt. The method separates the quantity of groups from the membership of those groups.

#### Choose the number of clusters offline

For each network, the authors collect attention observations on 1024 samples from [C4](https://md.research.elamur.ai/free/en/papers/raffel-2019-exploring-limits-transfer-learning-unified/). They vary the cluster count and inspect clustering error, described as the sum of squared distances to the nearest cluster. As more clusters are allowed, the representation can fit the observed head behavior more closely.

An elbow plot identifies where further increases in the cluster count yield relatively little improvement. The chosen point is where the error curve begins to flatten. The paper illustrates this analysis for several layers, emphasizing that the selected counts differ according to their observed redundancy.

This calibration happens once for each network. It does not update the network’s weights, and the authors do not repeat cluster-count selection for each evaluation dataset. That matters for interpretation: downstream results are not presented as the outcome of separately choosing a favorable grouping budget for every benchmark.

The procedure still requires judgment. An elbow is a pattern in an error curve, and the authors explicitly regard such analysis as unsuitable for repeated use during inference. CHAI gains practicality by moving this work away from the request path, rather than by eliminating the calibration decision.

#### Identify membership from the beginning of each request

Knowing the number of groups does not tell the system which heads should share a representative for the current input. Directly calculating all attention outputs and clustering them at every decoding step would defeat the intended saving. Full attention would already have been executed before the system decided which work could have been omitted.

CHAI resolves this through an initial observation period. For a new sequence, it uses ordinary multi-head attention while processing the first five tokens. The resulting activations support K-Means clustering with the layer-specific counts already chosen offline.

The authors motivate this choice through a membership-change analysis. Their plot indicates that assignments change relatively little when clustering is performed after the fifth token. This is an empirical persistence observation: an early grouping tends to remain useful over the continuation examined in the study.

After membership selection, the groups remain fixed throughout the request. CHAI does not repeatedly recluster every subsequent step. The benefit is that the cost of observing and clustering is paid once, while the reduced attention work continues afterwards.

The paper’s main procedural description distinguishes this online membership decision from offline count selection. A schematic caption is less precise about that distinction, but the repeated explanation in the method makes the intended division evident.

CHAI calibration and request execution The steps in order.

#### Execute clustered attention while preserving values

Once the grouping is fixed, a representative head supplies an attention calculation for its cluster. Redundant query and key work can be removed. The other heads’ value vectors remain available, so sharing a weighting pattern does not collapse all their information into the representative’s value representation.

This point explains both the benefit and its boundary. CHAI can shrink the key part of the cache associated with redundant heads. It cannot claim to remove the corresponding values, because the normal method explicitly preserves them. The reported key-and-value cache reduction is therefore a reduction in the combined storage total caused by eliminating selected keys.

The authors also emphasize that the resulting computation remains dense. Their implementation is built on Meta’s xFormers, and they do not rely on custom sparse GPU kernels to realize the sharing. That is a practical distinction from methods whose abstract operation count falls but whose hardware execution still requires specialized support.

No fine-tuning is part of this process. There is offline profiling and online clustering, both of which consume resources, but neither revises the learned parameters. CHAI is a runtime approximation chosen from observed behavior, with quality judged afterward through benchmark accuracy.

### Experiments and results

#### Networks, hardware, and evaluation tasks

The evaluation uses NVIDIA V100 GPUs. OPT-66B runs across eight GPUs on one node, LLaMA-33B uses four GPUs, and LLaMA-7B uses a single GPU. These conditions matter because a speedup is a property of an implementation and execution setting, not solely of a mathematical reduction in operations.

The accuracy experiments include PIQA and HellaSwag. They also include the challenge and easy portions of ARC, together with BoolQ. The corresponding source papers connect [PIQA](https://md.research.elamur.ai/free/en/papers/bisk-2019-piqa-reasoning-about-physical-commonsense/) to physical commonsense, [ARC](https://md.research.elamur.ai/free/en/papers/clark-2018-think-have-solved-question-answering/) to a reasoning challenge, and [BoolQ](https://md.research.elamur.ai/free/en/papers/clark-2019-boolq-exploring-surprising-difficulty-natural/) to natural yes-or-no questions. CHAI does not introduce a new evaluation collection.

The comparison includes original multi-head attention, the static CHAI variant, and request-specific CHAI. DejaVu is tested at several pruning settings on the LLaMA networks. SpAtten supplies an additional comparison involving token and head pruning.

The tables use an important reporting convention. The multi-head-attention row contains absolute task accuracy. Most subsequent rows contain changes relative to that baseline. A negative entry is therefore a reported loss from the baseline, not an absolute accuracy. Keeping this convention visible avoids reconstructing numbers that the paper does not explicitly print.

The paper does not clearly identify the evaluation split or provide uncertainty estimates for these accuracy tables. Their entries should consequently be read as the reported benchmark measurements under the described setup, without an invented claim about split selection or statistical significance.

#### OPT-66B: a setting where contextual pruning already works

OPT-66B serves in part as a reproduction check for DejaVu. The authors train its MLP prediction layers using the available implementation and evaluate the 50% sparsity setting. Their stated aim is to verify that their setup recovers the behavior reported by that comparison method.

The original attention baseline reports PIQA accuracy of 78.4 and HellaSwag accuracy of 71.1. Its ARC-Challenge accuracy is 41.6, while ARC-Easy is 64.7. BoolQ accuracy is 65.4. These are separate dataset measurements, instead of a single aggregate score.

For request-specific CHAI, the table records a PIQA change of -0.15 and a HellaSwag change of 0.1. Its changes on ARC-Challenge and ARC-Easy are 0.1 and -0.1, respectively. BoolQ changes by -0.6. The authors interpret this as close agreement with the original attention baseline.

The static grouping is less favorable across these entries. For example, the HellaSwag comparison below isolates the reported accuracy change on that dataset. Its split is not specified in the paper.

OPT-66B on HellaSwag, reported accuracy change from MHA Request-specific clustering preserves accuracy better than the fixed grouping.

**The numbers**

| System or setting | reported accuracy change |
| --- | --- |
| DejaVu-50% | -0.7 |
| CHAI-static | -1.7 |
| CHAI (this paper) | 0.1 |

This comparison supports the value of contextual membership without showing that every request improves. It also does not establish that the positive entry reflects a reliable general gain. No interval or repeated-run analysis accompanies the table.

#### LLaMA-7B: focused heads can still be redundant

The LLaMA-7B experiment is central to the authors’ argument that redundancy is a broader opportunity than uniform-attention pruning. Original multi-head attention achieves PIQA accuracy of 79.8 and HellaSwag accuracy of 76.1. ARC-Challenge is 47.5, ARC-Easy is 72.8, and BoolQ is 76.0.

For CHAI, the table gives a PIQA change of -2.0. The HellaSwag change is -3.2, and ARC-Challenge changes by -0.5. ARC-Easy and BoolQ have positive changes of 0.3 and 0.1. The result is therefore heterogeneous: some tasks lose accuracy, while others remain close enough to the baseline to show small positive entries.

DejaVu becomes substantially less accurate as sparsity increases in this setting. On HellaSwag, the table records -4.7 for its 10% setting, -18.6 for 30%, and -50.7 for 50%. CHAI-static records -4.3, while request-specific CHAI records -3.2.

LLaMA-7B on HellaSwag, reported accuracy change from MHA Contextual clustering incurs less loss than the tested pruning settings.

**The numbers**

| System or setting | reported accuracy change |
| --- | --- |
| DejaVu-10% | -4.7 |
| DejaVu-30% | -18.6 |
| DejaVu-50% | -50.7 |
| SpAtten | -42.5 |
| CHAI-static | -4.3 |
| CHAI (this paper) | -3.2 |

The comparison does not mean that every method removes the same amount of work. It demonstrates the observed quality consequences of the reported settings. A complete quality-versus-cost analysis would need to keep the degree of reduction visible alongside accuracy.

The surrounding prose states a maximum CHAI degradation of 3.7% for LLaMA-7B, while the CHAI row’s largest negative entry is -3.2. The article’s headline accuracy claim should therefore be read alongside the table rather than silently reconciled with that sentence.

#### LLaMA-33B: close baseline agreement

For LLaMA-33B, original attention records PIQA accuracy of 82.1 and HellaSwag accuracy of 82.8. The baseline ARC-Challenge result is 57.8, ARC-Easy is 80.0, and BoolQ is 83.1.

CHAI’s table entries remain close to those baselines. PIQA has a reported change of 0, HellaSwag has -0.14, and ARC-Challenge has -0.21. ARC-Easy changes by 0.9, while BoolQ changes by -0.04.

The static variant records larger losses on several tasks, including -3.7 for ARC-Easy. Request-specific clustering is therefore useful even where the overall deviations are small. The comparison is consistent with the method’s premise that a fixed offline grouping misses information about the particular request.

Again, the prose and table are not fully aligned. The evaluation discussion names 0.14% as the maximum degradation for this network, but the CHAI row also contains -0.21. Reporting both makes the uncertainty explicit without inventing a corrected headline.

#### Cache memory and latency

The paper reports up to 21.4% less combined key-and-value cache memory for LLaMA-7B. At a sequence length of 2048, it describes the original cache as around 1.2 GB, alongside around 12 GB for network weights. These figures show why cache reduction can matter even when it does not alter the much larger parameter storage.

The authors suggest that the released capacity could support longer contexts or more simultaneous requests. That is a plausible systems consequence, but the evaluation does not directly demonstrate a particular increase in serving concurrency or maximum context capacity.

Latency has two components: the time until the first token and the time until the next token. The former includes processing a fresh context and preparing its cached state. The latter concerns continuation when the relevant history is already cached. CHAI’s clustering overhead is included in the first-token discussion and excluded from the next-token measurement.

The latency claims contain inconsistencies. The first-token discussion reports up to 1.72× at sequence length 2048. Figure 12’s first-token caption instead gives 1.73×, which also appears in the abstract and conclusion. For next-token latency, the main discussion says over 5×, while the figure caption says up to 5×.

Those numbers should not be merged into one unqualified end-to-end speedup. They concern different timing boundaries, and the wording is not identical across the paper. The safe reading is that the authors observe faster execution, with larger benefits at longer sequences, while the precise headline depends on which statement and latency metric is being reported.

The authors cannot provide a hardware runtime comparison against DejaVu because the specialized kernels needed for that comparison were unavailable to them. Their accuracy comparison is therefore broader than their measured latency comparison. A prediction that low sparsity would yield limited speedup remains an argument, rather than a measured competing runtime.

### What the ablations show

#### Contextual membership improves on a fixed assignment

CHAI-static is the most direct test of the online membership decision. It keeps the grouping derived from offline observations instead of adapting membership to the current request. The cluster-count calibration is not the point of contrast; the important difference is which heads are assigned together.

Across the reported tables, request-specific CHAI generally preserves quality better. The LLaMA-7B HellaSwag entries show one example, while the ARC-Easy entries on LLaMA-33B show another. This supports the claim that average correlation does not fully describe the redundancy available in a particular input.

The comparison also clarifies what the offline stage contributes. Offline observations can indicate how much grouping a layer may tolerate, but they do not identify a universally best partition. CHAI’s architecture combines a stable capacity decision with contextual assignment because the evidence supports different levels of stability for those decisions.

This is stronger evidence than simply showing that correlated heads exist. Correlation plots establish an opportunity; the static-versus-dynamic comparison tests whether exploiting input dependence improves downstream quality. It connects the descriptive observation to a design choice.

#### Preserving values is essential to the chosen sharing boundary

The QKV experiment asks whether the entire head can be shared, rather than only its query and key behavior. In this variant, the selected representative’s value vector is reused as well. The authors call this CHAI-QKV.

Table 4 reports absolute accuracy for this experiment. On ARC-Challenge, ordinary attention achieves 47.5, CHAI records 47.0, and CHAI-QKV records 41.29. On PIQA, the corresponding entries are 79.8, 77.8, and 61.93. The much weaker QKV result is evidence that similar weighting does not make the values interchangeable.

PIQA accuracy in the value-sharing ablation Preserving separate values avoids the larger loss from sharing the full head.

**The numbers**

| System or setting | accuracy |
| --- | --- |
| MHA | 79.8 |
| CHAI (this paper) | 77.8 |
| CHAI-QKV | 61.93 |

The star identifies the paper’s principal method, not the highest accuracy in the comparison. Original attention remains the reference whose behavior the approximation is trying to retain.

This ablation is particularly informative because it identifies a failed extension of the main idea. A more aggressive sharing policy might appear attractive for memory reduction, but the experiment shows a substantial quality cost in the reported setting. The useful redundancy lies in a component of the operation, not necessarily in the entire head.

The result does not prove that values can never be compressed or shared. It shows that the specific representative-value substitution tested here is more damaging than CHAI’s narrower intervention. Other value-compression methods would require their own evidence.

#### The warm-up analysis supports amortization

Figure 9 examines how cluster membership changes as decoding proceeds. The authors observe relatively little change when clustering is performed beyond the fifth token, motivating their selected warm-up period.

The relevance is computational. If membership changed continually, CHAI would face a difficult choice between outdated assignments and repeated clustering. A stable early grouping allows the method to pay its observation cost once and reuse the decision.

The analysis supports the chosen heuristic in the studied setting. It does not supply a formal persistence guarantee, an accuracy bound for later reassignment, or a universal reason that every future sequence should stabilize at the same point. The paper’s method is empirical at this boundary.

There is also a distinction between membership stability and output fidelity. A grouping can remain unchanged while its approximation error changes. Conversely, a different assignment may produce similarly useful attention. The reported stability observation helps explain feasibility, but task accuracy remains necessary to judge the practical effect.

#### Layer-wise correlation explains unequal grouping budgets

The correlation plots compare layers using both averaged observations and a single example. Early layers show more diverse head behavior, while later layers exhibit more overlap. This supports the decision to avoid a uniform cluster count.

Figure 8 adds a second diagnostic: the relationship between the number of clusters and clustering error. The selected points reflect where additional groups cease to reduce error as sharply. The analysis links an operational choice to observed structure rather than choosing a global reduction ratio solely for convenience.

These plots are descriptive and calibration-oriented. They do not isolate every possible alternative cluster-selection policy. The paper does not demonstrate that the elbow choice is optimal under a formal cost-and-accuracy objective.

#### Cluster sizes are uneven

Figure 13 examines group sizes at Layer-18 of LLaMA-7B across C4 samples. The authors report that many heads often concentrate in a large cluster, with the remaining heads distributed less uniformly.

This matters because useful grouping need not look balanced. One common pattern can account for much of the repeated work, while a smaller set of heads retains distinctive attention. An approach that forced equally sized clusters could obscure that structure.

The observation also gives a more concrete interpretation of redundancy. CHAI is not merely pairing adjacent heads or imposing a neat architectural partition. It tries to capture a distribution of behavior that can be strongly skewed for a particular request.

#### Random grouping tests whether selection matters

The accuracy-versus-cost figures compare CHAI with static selection and random combinations. The appendix describes settings involving 4, 8, 16, and 24 heads. These comparisons ask whether an informed grouping provides a better tradeoff than simply combining progressively more heads.

The authors present CHAI as the stronger tradeoff in those plots. The available text does not give a complete numerical coordinate set for the curves, so the figures support a qualitative comparison here instead of a reconstructed table.

Together, the analyses form a coherent account of why the method works: redundancy exists, its amount differs by layer, its membership depends on context, and value representations must remain distinct. None of these findings alone establishes the full method. Their combination explains the particular boundary CHAI chooses.

### Limitations

#### Limits acknowledged or directly discussed by the authors

CHAI deliberately trades exact execution for approximate execution. The authors report task-accuracy changes and describe the method as preserving quality closely, instead of guaranteeing identical predictions. A useful speedup therefore has to be judged against the accuracy loss acceptable for the intended application.

The method also requires per-network calibration. Cluster counts come from offline activation collection and elbow analysis. This is cheaper than retraining in the sense relevant to the paper, but it is still preparation work that must be performed before the calibrated configuration can be used.

The online stage adds another cost. A request must supply enough initial observations to determine membership, and the clustering itself consumes time. The authors account for that overhead in their first-token discussion. Excluding it from next-token timing is reasonable for steady continuation, but does not make the overhead disappear from a complete request.

The authors explicitly retain every value vector. The resulting cache saving is consequently limited to the removable key state associated with redundant heads. Their own QKV comparison shows that extending sharing to representative values produces additional quality loss in the tested setting.

A further acknowledged evaluation restriction is the absence of DejaVu’s specialized kernels. CHAI is compared with that method on accuracy, but not through a corresponding hardware latency experiment. Claims about likely speed at particular sparsity settings should remain separate from measurements.

The paper also discusses compatibility with quantization as a possibility. It argues that preserving a quantized network’s behavior should leave room for attention sharing. It does not present a combined quantization-and-CHAI evaluation. Orthogonality of the basic ideas is not itself evidence for a particular combined speedup or quality result.

#### Limits visible in the experimental design

A careful reading should restrict the direct evidence to the evaluated architectures, tasks, and hardware. The study concerns decoder-only generation and the networks explicitly tested. It does not demonstrate the same behavior in transformer encoders, dependency parsers, or symbolic systems. Those are possible destinations for the broader ideas, not established applications.

The correlation evidence is also narrower than a guarantee of interchangeable function. Attention-score similarity describes one intermediate operation. It does not prove identical downstream activations, and the approximation formulation contains no theorem translating a clustering distance into a bound on benchmark accuracy.

The role of the representative is not specified with enough detail to support every implementation choice a reader might imagine. The paper explains grouping, K-Means membership, and representative attention sharing, but does not fully enumerate initialization, tie handling, or all selection rules in the method narrative. Reproducing the general concept is therefore easier than inferring every exact engineering decision from the equations alone.

The elbow criterion leaves room for judgment. The plotted error curves motivate the choices, but there is no formal optimization balancing clustering error, latency, memory, and task accuracy. Another calibration source or selection rule might choose different budgets. The reported absence of dataset-specific tuning is useful evidence of discipline, while still leaving this calibration sensitivity open.

The five-token warm-up is based on observed membership behavior. The paper does not establish that a fixed grouping remains adequate through arbitrary later changes in content. It also does not compare a broader family of monitoring and reclustering policies. Such policies would introduce their own overhead and might alter the practical tradeoff.

The accuracy tables do not include confidence intervals or a repeated-run variability analysis. Small positive changes should therefore not be presented as established improvements in capability. They show that the reported measurements can remain close to the original attention baseline, including occasional favorable entries.

The task suite does not establish every aspect of generated-text quality. Benchmark answer accuracy is relevant, but it does not by itself characterize long continuations, stylistic changes, factual reliability across open-ended outputs, or rare failures. CHAI’s approximation could affect those properties in ways not captured by the listed tasks.

Performance evidence needs similar boundaries. The latency experiments use the specified V100 environment and implementation. Dense computation and reduced attention work give a plausible reason for broader usefulness, but the assertion that benefits are independent of framework should not be read as a measured guarantee of the same speedup everywhere.

Reduced cache size may support more requests or longer contexts, as the authors suggest. Neither deployment benefit is directly quantified through a serving-capacity experiment. Total memory also includes the network weights and other execution state, so a cache reduction is not equivalent to the same reduction in total GPU memory use.

#### Reporting inconsistencies that affect interpretation

The most important reporting issue concerns maximum accuracy deviation. The abstract names 3.2%, the LLaMA-7B evaluation discussion names 3.7%, and the detailed CHAI row contains -3.2 as its largest negative entry. For LLaMA-33B, the prose names 0.14%, while the table includes -0.21.

These discrepancies should remain visible. Selecting one sentence and using it as an uncontested global guarantee would give the results more consistency than the paper actually presents. The task-level entries provide a more useful account of the observed tradeoff.

Latency reporting has a related problem. The first-token discussion uses 1.72×, while the corresponding caption uses 1.73×. The next-token discussion says over 5×, but its caption says up to 5×. Furthermore, the overall headline repeatedly emphasizes 1.73×.

The differences do not erase the evidence of acceleration, but they limit numerical precision in a high-level account. A responsible interpretation states the timing boundary, identifies whether clustering overhead is included, and preserves the distinction between the headline and the steady-state continuation claim.

Finally, the formal presentation has notation irregularities. These do not prevent understanding the algorithm, because the surrounding operational account repeatedly explains it. They do mean that the equations should be read as a description of the grouping objective, not as a complete formal specification with an error guarantee.

### What came after

[Cross-layer Attention Sharing for Pre-trained Large Language Models](https://md.research.elamur.ai/free/en/papers/mu-2026-cross-layer-attention-sharing-pre/) is a later citing work dated 2026. Its title identifies attention sharing across layers as its subject. That places it near CHAI’s broader concern with avoiding repeated attention work, while indicating a different structural axis from CHAI’s grouping of heads within a layer.

The available citation information does not establish how that work uses CHAI’s method. It gives no algorithmic description, measurements, or evidence that the later approach retains CHAI’s offline cluster counts, request-specific memberships, or value-preservation boundary. It would therefore be unwarranted to describe it as a demonstrated extension of those mechanisms.

The useful connection is a research question rather than an assumed lineage of results. CHAI shows how sharing can be selected from observed similarities in trained attention behavior. A cross-layer sharing study asks, by its title, about reuse across another part of the architecture. Whether that reuse requires the same similarity measures, preserves the same information, or offers comparable quality-and-cost tradeoffs must be established by the later work’s own evidence.

## Cite

Cite as Saurabh Agarwal, Bilge Acun, Basil Hosmer, Mostafa Elhoushi, Yejin Lee, Shivaram Venkataraman, Dimitris Papailiopoulos and Carole-Jean Wu. 2024. CHAI: Clustered Head Attention for Efficient LLM Inference. arXiv:2403.08058.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.48550/arxiv.2403.08058](https://doi.org/10.48550/arxiv.2403.08058) · [arXiv 2403.08058](https://arxiv.org/abs/2403.08058)

```bibtex
@misc{agarwal2024chai,
  title = {{CHAI: Clustered Head Attention for Efficient LLM Inference}},
  author = {Saurabh Agarwal, Bilge Acun, Basil Hosmer, Mostafa Elhoushi, Yejin Lee, Shivaram Venkataraman, Dimitris Papailiopoulos and Carole-Jean Wu},
  year = {2024},
  doi = {10.48550/arxiv.2403.08058},
  eprint = {2403.08058},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.2403.08058}
}
```

> 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)
