{"notes":[{"id":"transformers/mqa","category":"transformers","legacyPath":"transformers/1911-mqa","legacySlug":"1911-mqa","legacyPaths":[],"title":"MQA","subtitle":"Shared Key-Value Mechanism","author":"Z. Yuan","paperDate":"2019-11-06","publishedOn":"2024-09-27","paperTitle":"Fast Transformer Decoding: One Write-Head is All You Need","paperUrl":"https://arxiv.org/abs/1911.02150","bibliography":{"title":"Fast Transformer Decoding: One Write-Head is All You Need","authors":["Noam Shazeer"],"url":"https://arxiv.org/abs/1911.02150","pdfUrl":"https://arxiv.org/pdf/1911.02150","codeUrl":null,"preprint":{"id":"1911.02150","submittedOn":"2019-11-06","url":"https://arxiv.org/abs/1911.02150"},"publication":null,"citation":"@misc{transformersmqa2019,\n  title = {{Fast Transformer Decoding: One Write-Head is All You Need}},\n  author = {Noam Shazeer},\n  year = {2019},\n  eprint = {1911.02150},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/1911.02150}\n}\n","citationPath":"/content/papers/citations/transformers/mqa.4eadecef37e1.bib"},"thumbnail":{"src":"/content/papers/assets/5ab1f1a1fb117195cd8a34278d831e84062d528b60f38920e69726bdd39a5c8a.jpg","width":1328,"height":402},"locale":"en","path":"/content/papers/en/transformers/mqa.cfb096d5a320.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"revisiting-the-attention-mechanism","text":"Revisiting the Attention Mechanism","depth":2},{"id":"dot-product-attention","text":"Dot-Product Attention","depth":3},{"id":"multi-head-attention","text":"Multi-head Attention","depth":3},{"id":"batched-multi-head-attention","text":"Batched Multi-head Attention","depth":3},{"id":"incremental-multi-head-attention","text":"Incremental Multi-head Attention","depth":3},{"id":"solution","text":"Solution","depth":2},{"id":"multi-query-attention","text":"Multi-Query Attention","depth":3},{"id":"performance-analysis","text":"Performance Analysis","depth":3},{"id":"training-strategy","text":"Training Strategy","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"wmt14-en-de-results","text":"WMT14 EN-DE Results","depth":3},{"id":"inference-time-improvements","text":"Inference Time Improvements","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/transformer","relation":"background","topic":"Attention and the cost of autoregressive inference"},{"id":"deepseek/deepseek-v2","relation":"next","topic":"Attention and the cost of autoregressive inference"}]},{"id":"transformers/transformer","category":"transformers","legacyPath":"transformers/1706-transformer","legacySlug":"1706-transformer","legacyPaths":[],"title":"Transformer","subtitle":"The Dawn of a New Era","author":"Z. Yuan","paperDate":"2017-06-12","publishedOn":"2024-05-05","paperTitle":"Attention Is All You Need","paperUrl":"https://arxiv.org/abs/1706.03762","bibliography":{"title":"Attention Is All You Need","authors":["Ashish Vaswani","Noam Shazeer","Niki Parmar","Jakob Uszkoreit","Llion Jones","Aidan N. Gomez","Lukasz Kaiser","Illia Polosukhin"],"url":"https://arxiv.org/abs/1706.03762","pdfUrl":"https://arxiv.org/pdf/1706.03762","codeUrl":null,"preprint":{"id":"1706.03762","submittedOn":"2017-06-12","url":"https://arxiv.org/abs/1706.03762"},"publication":{"venue":"NeurIPS (NIPS)","year":2017,"kind":"conference","url":"https://proceedings.neurips.cc/paper_files/paper/2017/hash/3f5ee243547dee91fbd053c1c4a845aa-Abstract.html"},"citation":"@misc{transformerstransformer2017,\n  title = {{Attention Is All You Need}},\n  author = {Ashish Vaswani and Noam Shazeer and Niki Parmar and Jakob Uszkoreit and Llion Jones and Aidan N. Gomez and Lukasz Kaiser and Illia Polosukhin},\n  year = {2017},\n  eprint = {1706.03762},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/1706.03762}\n}\n","citationPath":"/content/papers/citations/transformers/transformer.86c0068d96fd.bib"},"thumbnail":{"src":"/content/papers/assets/29a55cb05497bdd9bbb3f3a96b7ed6656fda3552fa6a0fa5eb29e8e899c1acc1.jpg","width":756,"height":1080},"locale":"en","path":"/content/papers/en/transformers/transformer.420ab06f9af4.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"model-design","text":"Model Design","depth":3},{"id":"input-layer","text":"Input Layer","depth":3},{"id":"positional-encoding","text":"Positional Encoding","depth":3},{"id":"self-attention-mechanism","text":"Self-Attention Mechanism","depth":3},{"id":"multi-head-attention-mechanism","text":"Multi-Head Attention Mechanism","depth":3},{"id":"cross-attention-mechanism","text":"Cross-Attention Mechanism","depth":3},{"id":"feed-forward-network","text":"Feed-Forward Network","depth":3},{"id":"layer-normalization","text":"Layer Normalization","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"why-use-self-attention","text":"Why Use Self-Attention?","depth":3},{"id":"experimental-results-machine-translation","text":"Experimental Results: Machine Translation","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/flashattention","relation":"next","topic":"Attention memory and computation"},{"id":"transformers/bert","relation":"next","topic":"Pretraining bidirectional language representations"},{"id":"transformers/gpt_1","relation":"next","topic":"From language pretraining to in-context learning"}]},{"id":"deepseek/deepseek-v2","category":"deepseek","legacyPath":"deepseek/2405-deepseek-v2","legacySlug":"2405-deepseek-v2","legacyPaths":[],"title":"DeepSeek-V2","subtitle":"Cost-Effective Optimization","author":"Z. Yuan","paperDate":"2024-05-07","publishedOn":"2025-03-27","paperTitle":"DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model","paperUrl":"https://arxiv.org/abs/2405.04434v5","bibliography":{"title":"DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model","authors":["DeepSeek-AI"],"url":"https://arxiv.org/abs/2405.04434v5","pdfUrl":"https://arxiv.org/pdf/2405.04434v5","codeUrl":"https://github.com/deepseek-ai/DeepSeek-V2","preprint":{"id":"2405.04434","submittedOn":"2024-05-07","url":"https://arxiv.org/abs/2405.04434v5"},"publication":null,"citation":"@misc{deepseekdeepseekv22024,\n  title = {{DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model}},\n  author = {DeepSeek-AI},\n  year = {2024},\n  eprint = {2405.04434},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2405.04434v5}\n}\n","citationPath":"/content/papers/citations/deepseek/deepseek-v2.2792b9f48a76.bib"},"thumbnail":{"src":"/content/papers/assets/0c5c924a685f79d8a0037fb9862aa1358d05058a19ab295c1b1983dae491355d.jpg","width":1224,"height":984},"locale":"en","path":"/content/papers/en/deepseek/deepseek-v2.1b15b1df97c5.md","headings":[{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"multi-head-latent-attention","text":"Multi-head Latent Attention","depth":3},{"id":"decoupling-rotary-position-embedding","text":"Decoupling Rotary Position Embedding","depth":3},{"id":"deepseekmoe","text":"DeepSeekMoE","depth":3},{"id":"auxiliary-balance-loss","text":"Auxiliary Balance Loss","depth":3},{"id":"training-strategy","text":"Training Strategy","depth":3},{"id":"model-alignment","text":"Model Alignment","depth":2},{"id":"discussion","text":"Discussion","depth":2},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/mixtral","relation":"background","topic":"Routing tokens to sparse experts"},{"id":"deepseek/deepseek-llm","relation":"background","topic":"DeepSeek language models and reasoning training"},{"id":"deepseek/deepseek-v3","relation":"next","topic":"DeepSeek language models and reasoning training"}]}],"text":"In the age of the sharing economy, it seems that sharing can also be applied to the attention mechanism. This paper is authored by Noam Shazeer, one of the co-authors of the landmark paper \"Attention is All You Need.\"\n\n## Problem Definition\n\nIncremental decoding typically already caches past key/value projections. The remaining cost is repeatedly reading that growing KV cache at each step. This paper primarily addresses memory bandwidth, rather than merely eliminating repeated projection calculations.\n\nThe author identifies this as an inefficiency that can be optimized.\n\n## Revisiting the Attention Mechanism\n\nTo understand how the author improves this inefficiency, we first need to revisit the original attention mechanism.\n\n\n> [!TIP]\n> \n> Throughout this section, we’ll use the `einsum` operator extensively to represent matrix operations. If you're not familiar with this operator, you can refer to this article:\n> \n> - [**Einsum is All you Need**](https://rockt.github.io/2018/04/30/einsum)\n> \n> The paper uses `tf.einsum`; `torch.einsum` can express the same contractions. Porting the full code also requires changing tensors and APIs such as `softmax`, `concat` and `expand_dims`.\n> \n> Let’s assume you're already proficient with the `einsum` operator now.\n\n\n\n> [!WARNING]\n> \n> **Mathematical Warning:** The following sections contain detailed matrix operations. If you're not interested in the specifics, feel free to skip ahead to the conclusion:\n> \n> - [**Conclusion**](#conclusion)\n\n\nThese teaching examples follow the paper: the $1/\\sqrt{k}$ scale is absorbed into query/key projections and omitted in code. `mask` is additive: zero for allowed positions and negative infinity for forbidden ones, with at least one allowed position per query. Incremental caches start with an empty sequence dimension and append along that dimension. Repeated `concat` is illustrative; production kernels typically use preallocated caches.\n\n### Dot-Product Attention\n\nWe start with the dot-product attention mechanism, which deals with a single query vector and a set of key-value pairs.\n\n```python\nimport tensorflow as tf\n\ndef DotProductAttention(q, K, V):\n    \"\"\"\n    Dot-Product Attention on one query.\n    Args:\n    q: A vector of shape [k] (query)\n    K: A matrix of shape [m, k] (keys)\n    V: A matrix of shape [m, v] (values)\n\n    Returns:\n    y: A vector of shape [v] (output)\n    \"\"\"\n    # Compute dot-product between query q and key matrix K, resulting in logits of shape [m]\n    logits = tf.einsum(\"k,mk->m\", q, K)\n\n    # Apply softmax to logits to get the weights for each key, resulting in weights of shape [m]\n    weights = tf.nn.softmax(logits)\n\n    # Use the weights to compute a weighted sum of the value matrix V, resulting in output vector y of shape [v]\n    y = tf.einsum(\"m,mv->v\", weights, V)\n\n    return y\n```\n\nThis is the classic **dot-product attention mechanism**. It computes the similarity between the query and keys using a dot product and then applies those similarities as weights to the values, producing the final output.\n\n### Multi-head Attention\n\nNext, we look at multi-head attention, which combines several dot-product attention mechanisms to improve model performance.\n\nIn the function below, the parameter meanings are as follows:\n\n- $d$: The dimensionality of the query vector\n- $m$: The number of key-value pairs\n- $h$: The number of attention heads\n- $k$: The dimensionality of the linear projection for queries and keys\n- $v$: The dimensionality of the linear projection for values\n\n```python\nimport tensorflow as tf\n\ndef MultiheadAttention(x, M, P_q, P_k, P_v, P_o):\n    \"\"\"\n    Multi-head Attention on one query.\n\n    Args:\n    x: A vector of shape [d], representing the query\n    M: A matrix of shape [m, d], representing keys and values\n    P_q: A tensor of shape [h, d, k], representing the linear projection for queries\n    P_k: A tensor of shape [h, d, k], representing the linear projection for keys\n    P_v: A tensor of shape [h, d, v], representing the linear projection for values\n    P_o: A tensor of shape [h, d, v], representing the linear projection for output\n\n    Returns:\n    y: A vector of shape [d], representing the final output\n    \"\"\"\n\n    # Linear projection of query x, resulting in shape [h, k]\n    q = tf.einsum(\"d, hdk->hk\", x, P_q)\n\n    # Linear projection of keys and values in M\n    # K is of shape [h, m, k], and V is of shape [h, m, v]\n    K = tf.einsum(\"md, hdk->hmk\", M, P_k)\n    V = tf.einsum(\"md, hdv->hmv\", M, P_v)\n\n    # Compute logits as dot-product between query and key, resulting in shape [h, m]\n    logits = tf.einsum(\"hk, hmk->hm\", q, K)\n\n    # Apply softmax to compute attention weights, resulting in shape [h, m]\n    weights = tf.nn.softmax(logits)\n\n    # Use weights to compute a weighted sum of values, resulting in shape [h, v]\n    o = tf.einsum(\"hm, hmv->hv\", weights, V)\n\n    # Linear projection and combination of multi-head output, resulting in final output vector of shape [d]\n    y = tf.einsum(\"hv, hdv->d\", o, P_o)\n\n    return y\n```\n\n### Batched Multi-head Attention\n\nWe can extend this further to handle batched inputs, which is typical in training scenarios.\n\n```python\nimport tensorflow as tf\n\ndef MultiheadAttentionBatched(X, M, mask, P_q, P_k, P_v, P_o):\n    \"\"\"\n    Multi-head Attention for batched inputs.\n\n    Args:\n    X: A tensor of shape [b, n, d], representing query vectors (batch size b, sequence length n, vector dimension d)\n    M: A tensor of shape [b, m, d], representing keys and values (number of key-value pairs m)\n    mask: A tensor of shape [b, h, n, m], used to mask out invalid attention positions\n    P_q: A tensor of shape [h, d, k], representing the linear projection for queries\n    P_k: A tensor of shape [h, d, k], representing the linear projection for keys\n    P_v: A tensor of shape [h, d, v], representing the linear projection for values\n    P_o: A tensor of shape [h, d, v], representing the linear projection for output\n\n    Returns:\n    Y: A tensor of shape [b, n, d], representing the final output\n    \"\"\"\n\n    # Linear projection of query vectors X, resulting in shape [b, h, n, k]\n    Q = tf.einsum(\"bnd, hdk->bhnk\", X, P_q)\n\n    # Linear projection of keys and values in M, with keys K of shape [b, h, m, k] and values V of shape [b, h, m, v]\n    K = tf.einsum(\"bmd, hdk->bhmk\", M, P_k)\n    V = tf.einsum(\"bmd, hdv->bhmv\", M, P_v)\n\n    # Compute dot-product between query and key (logits), resulting in shape [b, h, n, m]\n    logits = tf.einsum(\"bhnk, bhmk->bhnm\", Q, K)\n\n    # Apply mask and softmax to compute attention weights, resulting in shape [b, h, n, m]\n    weights = tf.nn.softmax(logits + mask)\n\n    # Use weights to compute a weighted sum of values, resulting in shape [b, h, n, v]\n    O = tf.einsum(\"bhnm, bhmv->bhnv\", weights, V)\n\n    # Linear projection and combination of multi-head output, resulting in final output tensor of shape [b, n, d]\n    Y = tf.einsum(\"bhnv, hdv->bnd\", O, P_o)\n\n    return Y\n```\n\nAt this point, the author simplifies the assumptions for calculations and memory access:\n\n1. $m = n$: The number of key-value pairs $m$ is assumed to be equal to the sequence length $n$.\n2. $k = v = \\frac{d}{h}$: According to the Transformer paper, the dimension of the query and key $k$ is set equal to the dimension of the value $v$, and both are proportional to the feature dimension $d$, with the number of heads $h$ as the factor.\n3. $n ≤ d$: The sequence length $n$ is assumed to be less than or equal to the feature dimension $d$.\n\n---\n\nBased on these assumptions, the total computation complexity is $Θ(bnd^2)$, where $b$ is the batch size, $n$ is the sequence length, and $d$ is the feature dimension. This comes from the fact that each `tf.einsum` operation has a complexity of $O(bnd^2)$.\n\n\n> [!TIP]\n> \n> For example, if we have 1000 sequences, each with a length of 100 and a vector dimension of 512, the computation will be roughly $1000 \\times 100 \\times 512^2$.\n\n\nFor memory access, the total size of memory accessed is $O(bnd + bhn^2 + d^2)$:\n\n- The first term $bnd$ comes from the input $X$, the key-value matrix $M$, the query $Q$, key $K$, value $V$, output $O$, and the final output $Y$.\n\n- The second term $bhn^2$ comes from the logits and attention weights.\n- The third term $d^2$ comes from the projection tensors $P_q$, $P_k$, $P_v$, and $P_o$.\n\nThe ratio of memory access to computation is:\n\n$$\nO\\left(\\frac{1}{k} + \\frac{1}{bn}\\right)\n$$\n\nThe lower this ratio, the better performance on modern GPU/TPU hardware, which has significantly more computation power than memory bandwidth.\n\n### Incremental Multi-head Attention\n\nAnother variant is incremental multi-head attention, used in autoregressive generation.\n\n```python\nimport tensorflow as tf\n\ndef MultiheadSelfAttentionIncremental(x, prev_K, prev_V, P_q, P_k, P_v, P_o):\n    \"\"\"\n    Multi-head Self-Attention for one step in incremental generation.\n\n    Args:\n    x: A tensor of shape [b, d], representing the current query vector\n    prev_K: A tensor of shape [b, h, m, k], representing the previous key matrix\n    prev_V: A tensor of shape [b, h, m, v], representing the previous value matrix\n    P_q: A tensor of shape [h, d, k], representing the query projection matrix\n    P_k: A tensor of shape [h, d, k], representing the key projection matrix\n    P_v: A tensor of shape [h, d, v], representing the value projection matrix\n    P_o: A tensor of shape [h, d, v], representing the output projection matrix\n\n    Returns:\n    y: A tensor of shape [b, d], representing the current step output\n    new_K: A tensor of shape [b, h, m+1, k], representing the updated key matrix\n    new_V: A tensor of shape [b, h, m+1, v], representing the updated value matrix\n    \"\"\"\n\n    # Linear projection of query vector x, resulting in shape [b, h, k]\n    q = tf.einsum(\"bd, hdk->bhk\", x, P_q)\n\n    # Update the key matrix by appending the new key vector to the previous key matrix, resulting in shape [b, h, m+1, k]\n    new_K = tf.concat(\n        [prev_K, tf.expand_dims(tf.einsum(\"bd, hdk->bhk\", x, P_k), axis=2)],\n        axis=2\n    )\n\n    # Update the value matrix by appending the new value vector to the previous value matrix, resulting in shape [b, h, m+1, v]\n    new_V = tf.concat(\n        [prev_V, tf.expand_dims(tf.einsum(\"bd, hdv->bhv\", x, P_v), axis=2)],\n        axis=2\n    )\n\n    # Compute logits as dot-product between query and key, resulting in shape [b, h, m+1]\n    logits = tf.einsum(\"bhk, bhmk->bhm\", q, new_K)\n\n    # Compute attention weights using softmax, resulting in shape [b, h, m+1]\n    weights = tf.nn.softmax(logits)\n\n    # Compute weighted sum of values, resulting in shape [b, h, v]\n    o = tf.einsum(\"bhm, bhmv->bhv\", weights, new_V)\n\n    # Linear projection and combination of multi-head output, resulting in shape [b, d]\n    y = tf.einsum(\"bhv, hdv->bd\", o, P_o)\n\n    return y, new_K, new_V\n```\n\nThe author continues to use the simplified assumptions and evaluates the performance for incremental inference.\n\nIn this context, the total computation complexity is still $\\Theta(bnd^2)$, where $b$ is the batch size, $n$ is the sequence length, and $d$ is the feature dimension.\n\nThe total memory access is $\\Theta(bn^2d + nd^2)$:\n\n- The first term $bn^2d$ comes from reloading the key $K$ and value $V$ at every step, as these tensors grow with the sequence length $n$.\n- The second term $nd^2$ comes from the linear projection matrices $P_q$, $P_k$, $P_v$, and $P_o$.\n\nThe ratio of memory access to computation becomes:\n\n$$\n\\Theta\\left(\\frac{n}{d} + \\frac{1}{b}\\right)\n$$\n\nWhen $n ≈ d$ or $b ≈ 1$, this ratio approaches 1, indicating that memory bandwidth becomes the main bottleneck on modern hardware.\n\n---\n\nA straightforward optimization strategy is to increase the batch size, which reduces the memory access-to-computation ratio.\n\nAnother approach is to reduce the $\\frac{n}{d}$ ratio, which is more challenging since it involves reloading the key and value tensors at every step. Techniques include limiting the sequence length $n$ or computing attention only within a local window, reducing the number of positions to attend to.\n\n## Solution\n\nTo reduce the size of the key and value tensors, the author proposes removing the \"head\" dimension from the **keys** and **values** while retaining the multi-head structure for **queries**, reducing memory usage and improving efficiency.\n\n### Multi-Query Attention\n\n**Multi-Query Attention** is a variant of **Multi-Head Attention**. In traditional multi-head attention, each head has its own set of queries, keys, values, and outputs. In multi-query attention, however, all heads share a single set of keys and values, while only the queries maintain the multi-head structure. This reduces memory usage and improves inference speed.\n\n```python\nimport tensorflow as tf\n\ndef MultiQueryAttentionBatched(X, M, mask, P_q, P_k, P_v, P_o):\n    \"\"\"\n    Multi-Query Attention for batched inputs.\n\n    Args:\n    X: A tensor of shape [b, n, d], representing the query vectors\n    M: A tensor of shape [b, m, d], representing the key-value matrix\n    mask: A tensor of shape [b, h, n, m], used to mask invalid positions\n    P_q: A tensor of shape [h, d, k], representing the query projection matrix\n    P_k: A tensor of shape [d, k], representing the key projection matrix\n    P_v: A tensor of shape [d, v], representing the value projection matrix\n    P_o: A tensor of shape [h, d, v], representing the output projection matrix\n\n    Returns:\n    Y: A tensor of shape [b, n, d], representing the final output\n    \"\"\"\n\n    # Linear projection of query vectors X, resulting in shape [b, h, n, k]\n    Q = tf.einsum(\"bnd, hdk->bhnk\", X, P_q)\n\n    # Linear projection of keys and values, with keys K of shape [b, m, k] and values V of shape [b, m, v]\n    K = tf.einsum(\"bmd, dk->bmk\", M, P_k)\n    V = tf.einsum(\"bmd, dv->bmv\", M, P_v)\n\n    # Compute dot-product between query and key, resulting in shape [b, h, n, m]\n    logits = tf.einsum(\"bhnk, bmk->bhnm\", Q, K)\n\n    # Apply softmax to compute attention weights, considering the mask, resulting in shape [b, h, n, m]\n    weights = tf.nn.softmax(logits + mask)\n\n    # Compute weighted sum of values, resulting in shape [b, h, n, v]\n    O = tf.einsum(\"bhnm, bmv->bhnv\", weights, V)\n\n    # Final linear projection and combination of outputs, resulting in shape [b, n, d]\n    Y = tf.einsum(\"bhnv, hdv->bnd\", O, P_o)\n\n    return Y\n```\n\nThe author also provides an implementation for **Incremental Multi-Query Self-Attention**:\n\n```python\nimport tensorflow as tf\n\ndef MultiQuerySelfAttentionIncremental(x, prev_K, prev_V, P_q, P_k, P_v, P_o):\n    \"\"\"\n    Incremental Multi-Query Self-Attention for one step.\n\n    Args:\n    x: A tensor of shape [b, d], representing the current query vector\n    prev_K: A tensor of shape [b, m, k], representing the previous key matrix\n    prev_V: A tensor of shape [b, m, v], representing the previous value matrix\n    P_q: A tensor of shape [h, d, k], representing the query projection\n    P_k: A tensor of shape [d, k], representing the key projection\n    P_v: A tensor of shape [d, v], representing the value projection\n    P_o: A tensor of shape [h, d, v], representing the output projection\n\n    Returns:\n    y: A tensor of shape [b, d], representing the output\n    new_K: Updated key matrix, shape [b, m+1, k]\n    new_V: Updated value matrix, shape [b, m+1, v]\n    \"\"\"\n\n    # Linear projection of query vector, resulting in shape [b, h, k]\n    q = tf.einsum(\"bd, hdk->bhk\", x, P_q)\n\n    # Update key and value matrices\n    new_K = tf.concat([prev_K, tf.expand_dims(tf.einsum(\"bd, dk->bk\", x, P_k), axis=1)], axis=1)\n    new_V = tf.concat([prev_V, tf.expand_dims(tf.einsum(\"bd, dv->bv\", x, P_v), axis=1)], axis=1)\n\n    # Compute dot-product between query and key, resulting in shape [b, h, m+1]\n    logits = tf.einsum(\"bhk, bmk->bhm\", q, new_K)\n\n    # Compute softmax weights\n    weights = tf.nn.softmax(logits)\n\n    # Compute weighted sum of values\n    o = tf.einsum(\"bhm, bmv->bhv\", weights, new_V)\n\n    # Linear projection and combination of outputs\n    y = tf.einsum(\"bhv, hdv->bd\", o, P_o)\n\n    return y, new_K, new_V\n```\n\n### Performance Analysis\n\nJust like traditional multi-head attention, the computational complexity in incremental multi-query attention remains $\\Theta(bnd^2)$, but the memory access is now $\\Theta(bnd + bn^2k + nd^2)$.\n\nRemoving the \"head\" dimension from keys and values shrinks the KV cache repeatedly read during incremental decoding. The asymptotic arithmetic cost remains $\\Theta(bnd^2)$; the speed gain comes mainly from lower memory-bandwidth demand.\n\n\n> [!TIP]\n> \n> With $h=8$ and $k=v=64$, the KV cache per position and layer falls from $h(k+v)$ elements to $k+v$, one eighth as many. Compare this with incremental MHA’s $\\Theta(bn^2d+nd^2)$ access cost, not the earlier batched formula. Attention logits still retain $h$ query heads.\n\n\nThe ratio of memory access to computation becomes:\n\n$$\n\\Theta\\left(\\frac{1}{d} + \\frac{n}{dh} + \\frac{1}{b}\\right)\n$$\n\nSince the $\\frac{n}{d}$ term is now reduced by a factor of $h$, the performance of incremental inference improves significantly.\n\n\n> [!TIP]\n> \n> \n> - **Traditional Multi-Head Attention Ratio**: $\\Theta\\left(\\frac{n}{d} + \\frac{1}{b}\\right)$\n> \n>   In traditional multi-head attention, the ratio of memory access to computation is influenced by the sequence length $n$ and the feature dimension $d$. When the sequence length approaches the feature dimension, this ratio nears 1, meaning memory access becomes the bottleneck for performance.\n> \n> - **Multi-Query Attention Ratio**: $\\Theta\\left(\\frac{1}{d} + \\frac{n}{dh} + \\frac{1}{b}\\right)$\n> \n>   By reducing the dimensions of the keys and values, the $\\frac{n}{d}$ term is reduced by a factor of $h$. For example, with $h = 8$, the memory access is significantly lower, resulting in faster inference.\n> \n\n\nSuppose you're working with a language model that processes a batch of $b = 128$ sequences, each with 100 tokens (sequence length $n = 100$) and each token having a vector dimension of $d = 512$.\n\nFor traditional multi-head attention, the \"memory access-to-computation ratio\" might be:\n\n$$\n\\frac{n}{d} + \\frac{1}{b} = \\frac{100}{512} + \\frac{1}{128} \\approx 0.1953 + 0.0078 = 0.2031\n$$\n\nFor multi-query attention, assuming $h = 8$, this ratio becomes:\n\n$$\n\\frac{1}{d} + \\frac{n}{dh} + \\frac{1}{b}\n$$\n\n$$\n= \\frac{1}{512} + \\frac{100}{512 \\times 8} + \\frac{1}{128}\n$$\n\n$$\n\\approx 0.00195 + 0.0244 + 0.0078 = 0.03415\n$$\n\nThese substitutions illustrate a cost model with constants omitted; actual speedup requires measurement. MQA reduces KV traffic, while actual performance depends on batch size, kernels and hardware.\n\n### Training Strategy\n\nThe author evaluates the approach using the WMT 2014 English-to-German translation task.\n\nThey use a 6-layer encoder-decoder Transformer model with the following configuration:\n\n- $d_{model} = 1024$\n- $d_{ff} = 4096$\n- Number of heads $h = 8$\n- $d_k = d_v = 128$ with learned positional embeddings, and weight sharing between the token embedding layer and the output layer.\n\nTraining is done for 100,000 steps (20 epochs), with each batch containing 128 samples, each with an input sequence of 256 tokens and a target sequence of 256 tokens. The model is trained on a 32-core TPUv3 pod, with training taking approximately 2 hours per model.\n\nIn the multi-query attention model (MQA), the author replaces all the attention layers with multi-query attention and increases the hidden dimension of the feed-forward layers from 4096 to 5440 to maintain the total number of parameters as the baseline model.\n\n## Discussion\n\n### WMT14 EN-DE Results\n\n![WMT14 EN-DE](/content/papers/assets/3d1e9e9261ce905542bd60501f51c5b8e7f84b8120cb882ef51e990eb01e38a5.jpg)\n\nOn the development set, MQA is slightly worse: ln(PPL) 1.439 versus 1.424 and BLEU 26.5 versus 26.7. It stays closer to the baseline than reducing head counts or dimensions. Test-set beam-4 BLEU is actually 28.5 for MQA versus 28.4 for the baseline, so not every metric decreases.\n\n### Inference Time Improvements\n\n![Inference Time](/content/papers/assets/5ab1f1a1fb117195cd8a34278d831e84062d528b60f38920e69726bdd39a5c8a.jpg)\n\nSpeed is measured on **TPUv2 (8 cores)**. Each training step contains 32,768 input tokens plus 32,768 target tokens. Dividing by 32,768 below gives amortized cost per input/target token pair.\n\n- **Baseline model**: Each training step takes **433ms**.\n- **Multi-query model**: Each training step takes **425ms**, slightly faster than the baseline.\n\nThe per-token training time is:\n\n- **Baseline model**:\n\n  $$\n  \\frac{433\\,\\mathrm{ms}}{32{,}768} \\approx 13.2\\,\\mu\\mathrm{s}\n  $$\n\n- **MQA model**:\n\n  $$\n  \\frac{425\\,\\mathrm{ms}}{32{,}768} \\approx 13.0\\,\\mu\\mathrm{s}\n  $$\n\n---\n\nIn the case of autoregressive generation, tested with 1024 sequences (each with 128 tokens, with each TPU core processing 128 sequences), the speed of incremental greedy decoding was measured:\n\n- **Baseline model**:\n\n  - The encoder took **222ms**, which translates to **1.7µs** per token.\n  - The decoder took **47ms** per step, translating to **46µs** per token.\n\n- **MQA model**:\n\n  - The encoder took **195ms**, translating to **1.5µs** per token.\n  - The decoder took **3.9ms** per step, translating to **3.8µs** per token, significantly faster than the baseline.\n\n## Conclusion\n\nFast and efficient!\n\nIn this TPUv2 greedy-decoding experiment with batch 1024 and length 128, decoder steps fall from 47 ms to 3.9 ms, about a 12-fold speedup. Amortized time per token is not single-user token latency, and the same gain is not guaranteed on other hardware or batch sizes.\n\n\n> [!TIP]\n> \n> This architecture was later adopted in `MobileNet V4`. Interested readers can check out the following article:\n> \n> - [**[24.04] MobileNet-V4: Five Years of Evolution**](/blog/papers/lightweight/mobilenet-v4#mobile-mqa)\n","imageSizes":{"/content/papers/assets/3d1e9e9261ce905542bd60501f51c5b8e7f84b8120cb882ef51e990eb01e38a5.jpg":{"width":1268,"height":528},"/content/papers/assets/5ab1f1a1fb117195cd8a34278d831e84062d528b60f38920e69726bdd39a5c8a.jpg":{"width":1328,"height":402}}}
