Attention Head Calculator

Calculate multi-head attention parameters and requirements.

Attention Configuration

Attention Parameters

2.36M

Head Dimension: 64

GFLOPs
26.27
💾KV Cache Savings
0.0%

Parameter Breakdown

Query Projection (W_Q)0.59M
Key Projection (W_K)0.59M
Value Projection (W_V)0.59M
Output Projection (W_O)0.59M

Memory Usage

Attention Scores384.00 MB
Q Tensor48.00 MB
KV Tensors96.00 MB

What the Attention Head Calculator Does

The attention head calculator sizes the multi-head attention block that sits at the heart of every transformer model. Self-attention is the operation that lets a language model decide which earlier tokens matter when predicting the next one, and it is split across several parallel attention heads so the model can attend to different patterns at the same time. This calculator takes the dimensions of that block (hidden size, number of heads, sequence length, batch size, and the attention variant) and returns the projection parameter count, the activation memory footprint, the floating-point operations (FLOPs) per attention pass, and the key-value cache savings you gain from grouped or multi-query attention.

Why does this matter? When you scale a transformer, the attention block is where compute and memory grow quadratically with sequence length. A model that runs comfortably at a 512-token context can run out of GPU memory at 8,192 tokens purely because the attention score matrix is sized as sequence length squared. Knowing these numbers before you launch a training run or deploy an inference server is the difference between a job that fits and a job that crashes with an out-of-memory error. The calculator turns the raw transformer attention formulas into instant, concrete figures.

The tool supports three attention mechanisms used across modern large language models. Multi-Head Attention (MHA) is the original design from the 2017 transformer paper, where every query head has its own dedicated key and value head. Grouped Query Attention (GQA) shares each key-value head across a group of query heads, cutting the key-value cache without the quality loss of going all the way down. Multi-Query Attention (MQA) is the extreme case where a single key-value head serves every query head, giving the largest cache savings. Because the calculator models all three, you can directly compare how a design choice changes parameters, memory, and the KV cache that dominates inference cost.

Everything below explains the exact math the calculator runs, with worked examples that reproduce the on-screen numbers. Use it to plan attention configurations, debug memory limits, or simply understand how transformer attention scales. The attention head calculator weaves together the parameter, memory, FLOPs, and KV-cache views that you would otherwise have to compute by hand across several formulas.

How the Calculator Computes Attention Sizes

The attention head calculator starts from five inputs: the hidden size d (also called d_model), the number of query heads h, the number of key-value heads kvH (only used for GQA and MQA), the sequence length, and the batch size. From these it derives every result.

The head dimension is simply the hidden size divided by the number of query heads, headDim = d / h. This is the width of the vector each individual head works with, and it is almost always a power-friendly number like 64 or 128. The four learned projection matrices (query, key, value, and output) are each sized from the hidden dimension. In MHA every projection is a square d × d matrix, so each contributes parameters and the attention block holds 4d² weights in total. In GQA and MQA the key and value projections shrink because they only produce kvH heads of width headDim, so each becomes d × headDim × kvH parameters instead of .

The calculator also reports activation memory, which is the temporary tensors created during a forward pass. The attention score matrix is the expensive one: it is shaped batch × heads × sequence × sequence in fp32, so its size scales with the square of the sequence length. The query, key, and value tensors are linear in sequence length. Finally, the FLOPs estimate adds the cost of the query-key product, the softmax, and the weighted value sum. The KV cache savings figure compares the key-value cache an MHA model would need against the smaller cache of your chosen variant, expressed as a percentage reduction.

Inputs and their roles

  • Hidden Size (d_model): the embedding width of the model; drives projection parameters.
  • Number of Query Heads: how many parallel attention heads the queries use; sets the head dimension.
  • Number of KV Heads: how many key-value heads exist (equals query heads for MHA, fewer for GQA, one for MQA).
  • Sequence Length: tokens processed at once; the quadratic memory driver.
  • Batch Size: sequences processed in parallel; scales all activation memory linearly.

Attention Projection Parameters

totalParams = qParams + kParams + vParams + outputParams

Where:

  • qParams= Query projection weights = d × d
  • kParams= Key projection = d² for MHA, or d × (d/h) × kvH for GQA/MQA
  • vParams= Value projection = d² for MHA, or d × (d/h) × kvH for GQA/MQA
  • outputParams= Output projection weights = d × d
  • d= Hidden size (d_model)
  • h= Number of query heads
  • kvH= Number of key-value heads

Memory and FLOPs Behind Attention

Two costs dominate the attention block: the memory it allocates and the floating-point work it performs. The attention head calculator reports both so you can predict whether a configuration fits on your hardware.

The largest activation is the attention score matrix. After multiplying queries by keys you get a matrix of similarity scores with shape batch × heads × sequence × sequence, and the calculator assumes fp32 (4 bytes). This is why doubling the context length roughly quadruples this tensor. The query tensor is sized batch × heads × sequence × headDim, while the key and value tensors together take twice that. In GQA and MQA the key-value tensors shrink in proportion to the smaller key-value head count, which is exactly where inference savings come from.

The compute side is captured by the GFLOPs figure. The query-key product costs 2 × batch × heads × sequence² × headDim operations, the softmax adds roughly 5 × batch × heads × sequence², and the weighted sum over values costs another 2 × batch × heads × sequence² × headDim. Summing these and dividing by one billion gives GFLOPs. Notice that the two matrix multiplies both scale with the square of the sequence length, which is the well-known quadratic bottleneck of self-attention. Techniques such as FlashAttention reduce the memory traffic of these operations without changing this FLOP count, so the calculator's GFLOPs remain a useful upper-bound estimate for planning.

Quantity Formula Scaling
Attention scores batch × h × seq² × 4 bytes Quadratic in sequence
Q tensor batch × h × seq × headDim × 4 Linear in sequence
KV tensors 2 × batch × kvH × seq × headDim × 4 Linear; shrinks with kvH
Attention FLOPs 4 × batch × h × seq² × headDim + 5 × batch × h × seq² Quadratic in sequence

MHA vs GQA vs MQA: Choosing an Attention Variant

The single biggest lever in this calculator is the attention type, because it directly controls the key-value cache that dominates the cost of serving large language models. During generation the model must keep the keys and values for every token already produced. That cache grows with sequence length and with the number of key-value heads, so reducing the key-value head count is the cleanest way to make long-context inference affordable.

Multi-Head Attention (MHA) uses one key-value head per query head, giving the richest representation but the largest cache. Grouped Query Attention (GQA) divides the query heads into groups that share a key-value head; with 32 query heads and 8 key-value heads, four queries share each key-value pair, cutting the cache by 75% while keeping most of MHA's quality. Multi-Query Attention (MQA) takes this to the limit with a single key-value head, often saving well over 90% of the cache at the cost of some accuracy. Models like Llama 2 70B and many production chat models adopt GQA precisely because it sits in the sweet spot between cache size and quality.

The calculator quantifies this trade-off with the KV cache savings percentage and the query heads per KV head ratio. Because the key and value projection matrices also shrink under GQA and MQA, you save parameters too, though the bulk of the benefit shows up at inference time as a smaller cache and higher throughput. If you are unsure which variant to pick, start with GQA: it preserves nearly all of MHA's modeling power while delivering most of MQA's memory advantage.

Quick decision guide

  • Maximum quality, short context: stay with MHA.
  • Long context, production serving: use GQA with 4 to 8 query heads per KV head.
  • Extreme memory limits or edge inference: consider MQA and validate the quality drop.

Reading and Acting on the Results

Each output panel in the attention head calculator maps to a real engineering decision. The headline attention parameters figure (in millions) is the weight count of one attention block; multiply it by the number of transformer layers to estimate the attention share of total model size. The head dimension tells you the width each head operates on, and you generally want it to stay at 64 or 128 so the math maps cleanly onto GPU tensor cores.

The GFLOPs value is the compute for a single attention pass at your batch and sequence settings. If you compare two configurations and the GFLOPs jump sharply, it is almost always because you increased the sequence length, which scales the cost quadratically. The parameter breakdown separates the query, key, value, and output projections; under GQA and MQA you will see the key and value rows drop while query and output stay fixed, which visually explains where the savings come from.

The memory usage panel lists the attention score matrix, the query tensor, and the key-value tensors. When the attention score number looks alarmingly large, that is the quadratic term shouting at you, and it is the signal to either shorten the context, reduce the batch, or adopt a memory-efficient attention kernel. Finally, the KV cache savings percentage is your inference cheat sheet: a 75% saving means the serving cache is a quarter of what MHA would need, which roughly translates into supporting four times the batch size or context at the same memory budget. Treat these figures as planning estimates rather than exact production numbers, since real frameworks add overheads and may use lower-precision formats than the fp32 assumed here.

Worked Examples

Default MHA Block (BERT-base style)

Problem:

Compute the attention parameters, head dimension, GFLOPs, and KV cache savings for hidden size 768, 12 query heads, sequence length 512, batch size 32, using Multi-Head Attention.

Solution Steps:

  1. 1Head dimension = d / h = 768 / 12 = 64.
  2. 2Each projection (Q, K, V, output) = d² = 768 × 768 = 589,824 parameters; with MHA all four are equal.
  3. 3Total parameters = 4 × 589,824 = 2,359,296 ≈ 2.36M.
  4. 4GFLOPs = (4 × 32 × 12 × 512² × 64 + 5 × 32 × 12 × 512²) / 1e9 ≈ 26.27 GFLOPs; KV savings = 0% because kvH equals h.

Result:

2.36M attention parameters, head dimension 64, about 26.27 GFLOPs, and 0% KV cache savings.

GQA Block (Llama-style 70B layer)

Problem:

Compute parameters and KV cache savings for hidden size 4096, 32 query heads, 8 KV heads, sequence length 2048, batch size 1, using Grouped Query Attention.

Solution Steps:

  1. 1Head dimension = 4096 / 32 = 128; query heads per KV head = 32 / 8 = 4.
  2. 2Query and output projections each = d² = 4096 × 4096 = 16,777,216 ≈ 16.78M.
  3. 3Key and value projections each = d × (d/h) × kvH = 4096 × 128 × 8 = 4,194,304 ≈ 4.19M.
  4. 4Total = 16.78M + 4.19M + 4.19M + 16.78M ≈ 41.94M; KV savings = (1 − 8/32) × 100 = 75%.

Result:

41.94M parameters, head dimension 128, 4 query heads per KV head, and 75% KV cache savings versus MHA.

MQA Block for Maximum Cache Savings

Problem:

Compute the key/value projection size and KV cache savings for hidden size 4096, 32 query heads, 1 KV head, sequence length 1024, batch size 1, using Multi-Query Attention.

Solution Steps:

  1. 1Head dimension = 4096 / 32 = 128; with MQA there is a single shared KV head.
  2. 2Key and value projections each = d × (d/h) × kvH = 4096 × 128 × 1 = 524,288 ≈ 0.52M.
  3. 3Query and output projections remain d² = 16,777,216 ≈ 16.78M each.
  4. 4KV savings = (1 − 1/32) × 100 = 96.875%, since only 1 of 32 KV heads is kept.

Result:

Each KV projection is about 0.52M parameters and the KV cache shrinks by 96.875% compared with MHA.

Scaling Sequence Length on Attention Memory

Problem:

For hidden size 1024, 16 heads, batch size 8 MHA, show how the attention score memory changes from a 1024-token to a 2048-token context.

Solution Steps:

  1. 1At seq 1024: attention scores = batch × h × seq² × 4 = 8 × 16 × 1024² × 4 bytes = 512 MB.
  2. 2At seq 2048: attention scores = 8 × 16 × 2048² × 4 bytes = 2048 MB (2 GB).
  3. 3Doubling the sequence from 1024 to 2048 quadrupled the score memory (512 MB → 2048 MB).
  4. 4This confirms the quadratic scaling: attention score memory grows with sequence length squared.

Result:

Attention score memory rises from 512 MB to 2,048 MB, a 4× increase for a 2× longer context.

Tips & Best Practices

  • Keep the head dimension at 64 or 128 by choosing a hidden size divisible by your head count.
  • Watch the attention score memory first when raising sequence length, since it grows quadratically.
  • Switch to GQA with 4 to 8 query heads per KV head to cut inference cache with minimal quality loss.
  • Reserve MQA for tight memory budgets, and test accuracy before committing to a single KV head.
  • Multiply the attention parameter count by your layer count to estimate the attention share of model size.
  • Lower the batch size if the attention score tensor pushes you over GPU memory at long contexts.
  • Remember the calculator assumes fp32 activations; using bf16 halves the real activation memory.

Frequently Asked Questions

The head dimension is the hidden size divided by the number of query heads (headDim = d / h). It is the width of the vector each attention head works with. Designers pick hidden size and head counts so the head dimension lands on 64 or 128, because those sizes map efficiently onto GPU tensor cores and keep each head expressive enough to learn useful patterns.
It sums the query, key, value, and output projection matrices. In Multi-Head Attention each is a square d × d matrix, giving 4d² total weights. In GQA and MQA the key and value matrices shrink to d × (d/h) × kvH because they produce fewer heads, so the total drops while the query and output projections stay the same size.
The attention score matrix has shape batch × heads × sequence × sequence, so its size depends on the square of the sequence length. Doubling the context roughly quadruples this tensor, which is the well-known quadratic bottleneck of self-attention. The query, key, and value tensors only grow linearly, so the score matrix is what usually triggers out-of-memory errors at long contexts.
It compares the key-value cache that Multi-Head Attention would require against the smaller cache of your chosen variant, expressed as a percentage reduction. With 32 query heads and 8 KV heads, GQA keeps a quarter of the cache, so the calculator reports 75% savings. A higher percentage means more memory freed for longer contexts or larger batches during inference.
Use Multi-Head Attention when you want maximum quality and contexts are short. Choose Grouped Query Attention for production serving of long contexts, since it cuts the cache substantially while preserving nearly all of MHA's accuracy. Reserve Multi-Query Attention for extreme memory constraints, and validate that the quality loss from a single KV head is acceptable for your task.
They are planning estimates that match the formulas shown on this page, using fp32 (4 bytes) for activations. Real frameworks add overhead, may store tensors in fp16 or bf16, and use kernels like FlashAttention that change the memory traffic. Treat the calculator's output as a reliable upper bound for budgeting hardware rather than a guaranteed runtime measurement.

Sources & References

Last updated: 2026-06-05

💡

Help us improve!

How would you rate the Attention Head Calculator?

<>

Editorial Note

MyCalcBuddy Editorial Team

This page is maintained as an educational calculator reference.

Source

Formula Source: Standard Mathematical References

by Various

UpdatedLast reviewed: May 2026
CheckedFormula checks are based on standard references and internal QA review.