SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2502.14837 · ACL · 2025

Towards Economical Inference: Enabling DeepSeek's Multi-Head Latent Attention in Any Transformer-based LLMs

Qi Zhang, Xipeng Qiu, Qipeng Guo, Bin Guo, Tao Gui, Tao Ji, Yuanbin Wu, Zhan Chen, Lixing Shen

arXiv · PDF · Open in the Atlas

Code that ran

10 of 15 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 10 have no contract verdict; 0 failures of our instrument; 5 no recorded run), measured 2026-11-22; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2502.14837.json · badge: /api/ran/2502.14837.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
JT-Ushio/MHA2MLA canonical (classifier label)
classifier basis not recorded on the link
10 ran · 5 no recorded run
FunctionStatusWhere it lives
SVD Ran
ran on a synthesized input
JT-Ushio/MHA2MLA/src/mha2mla/patch_func.py
code served (permissive licence) · get_code("d1722a47a6e68260")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# Create a small matrix X with distinct dimensions (5x4)
# SVD will decompose this into U (5x4), S (4,), V (4x4) with full_matrices=False
X = torch.randn(5, 4)

# r is the rank to keep (must be <= min(5, 4) = 4)
r = 2

ARGS = {
    "X": X,
    "r": r,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
create_custom_apply_rotary_pos_emb Ran
ran on a synthesized input
JT-Ushio/MHA2MLA/src/mha2mla/patching_llama.py
code served (permissive licence) · get_code("bd8982c35600a2b7")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned function. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Create q_r_indices and k_r_indices
# These should be lists of tensors, one per layer, containing indices for dimension selection
# The function uses layer_idx to index into these lists
num_layers = 2
head_dim = 4

# Create index tensors for query and key rotary embeddings
# These indices select which dimensions to use from the rotary embeddings
q_r_indices = [torch.tensor([0, 1, 2, 3]) for _ in range(num_layers)]
k_r_indices = [torch.tensor([0, 1, 2, 3]) for _ in range(num_layers)]

ARGS = {
    "q_r_indices": q_r_indices,
    "k_r_indices": k_r_indices,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type function — a function output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a function output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
create_custom_apply_rotary_pos_emb Ran
ran on a synthesized input
JT-Ushio/MHA2MLA/src/mha2mla/patching_qwen2.py
code served (permissive licence) · get_code("f73327d915050f1a")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned function. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Number of layers and head dimensions
num_layers = 2
head_dim = 4
num_heads = 3
seq_len = 5

# Create q_r_indices and k_r_indices
# These should be lists of tensors, one per layer, containing indices into the head_dim
q_r_indices = [torch.tensor([0, 1, 2, 3]) for _ in range(num_layers)]
k_r_indices = [torch.tensor([3, 2, 1, 0]) for _ in range(num_layers)]

ARGS = {
    "q_r_indices": q_r_indices,
    "k_r_indices": k_r_indices,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type function — a function output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a function output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
create_custom_apply_rotary_pos_emb Ran
ran on a synthesized input
JT-Ushio/MHA2MLA/src/mha2mla/patching_qwen3.py
code served (permissive licence) · get_code("4b3aa5813125a737")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned function. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
import inspect

torch.manual_seed(0)

# Build q_r_indices and k_r_indices
# These should be lists of tensors, one per layer
# Each tensor contains indices into the head_dim
num_layers = 2
head_dim = 4
batch_size = 2
seq_len = 3
num_heads = 2

q_r_indices = [torch.tensor([0, 1, 2, 3]) for _ in range(num_layers)]
k_r_indices = [torch.tensor([3, 2, 1, 0]) for _ in range(num_layers)]

ARGS = {
    "q_r_indices": q_r_indices,
    "k_r_indices": k_r_indices,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type function — a function output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a function output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
create_custom_apply_rotary_pos_emb Ran
ran on a synthesized input
JT-Ushio/MHA2MLA/src/mha2mla/patching_qwen3_moe.py
code served (permissive licence) · get_code("e3be3d316dce65ea")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned function. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Create small tensors for q, k, cos, sin
# q, k shape: [batch_size, seq_len, heads, head_dim] or similar
# cos, sin shape: [batch_size, seq_len, head_dim]

batch_size = 2
seq_len = 3
num_heads = 4
head_dim = 8

# q and k tensors: [batch_size, num_heads, seq_len, head_dim]
q = torch.randn(batch_size, num_heads, seq_len, head_dim)
k = torch.randn(batch_size, num_heads, seq_len, head_dim)

# cos and sin tensors for rotary embeddings: [batch_size, seq_len, head_dim]
cos = torch.randn(batch_size, 1, head_dim)
sin = torch.randn(batch_size, 1, head_dim)

# Create index tensors for q and k rotary indices
# q_r_indices and k_r_indices should be lists of tensors, one per layer
# Each tensor contains indices for selecting head_dim values
num_layers = 2
q_r_indices = [torch.arange(head_dim // 2) for _ in range(num_layers)]
k_r_indices = [torch.arange(head_dim // 2, head_dim) for _ in range(num_layers)]

ARGS = {
    "q_r_indices": q_r_indices,
    "k_r_indices": k_r_indices,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type function — a function output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a function output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
create_hook_fn Ran
ran on a synthesized input
JT-Ushio/MHA2MLA/src/mha2mla/2_norm.py
code served (permissive licence) · get_code("3e838680cc326966")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned function. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# The function create_hook_fn takes a single parameter: 'name'
# Looking at the function body:
# - It takes a parameter 'name' which is used as a dictionary key
# - It returns a hook function that will be called with (module, args, kwargs, output)
# - The hook accesses kwargs['hidden_states'] and stores it in hidden_states_dict[name]

# So we need to provide a valid 'name' argument - a string identifier
name = "test_layer"

ARGS = {
    "name": name
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type function — a function output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a function output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
generate_random_input_ids Ran
ran on a synthesized input
JT-Ushio/MHA2MLA/eval/benchmark_latency_memory.py
code served (permissive licence) · get_code("c72933732661bbe4")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 2, dtype family int, shape (2, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

ARGS = {
    "batch_size": 2,
    "input_length": 4,
    "vocab_size": 100,
    "device": "cpu"
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family int, shape (2, 4) — shape (2, 4) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
partial_rope_mask Ran
ran on a synthesized input
JT-Ushio/MHA2MLA/src/mha2mla/patch_func.py
code served (permissive licence) · get_code("818485f3147eb543")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import tempfile
import os

torch.manual_seed(0)

class ModelArgs:
    def __init__(self):
        self.num_attention_heads = 8
        self.num_key_value_heads = 2
        self.hidden_size = 64
        self.head_dim = 8

class MHA2MLAArgs:
    def __init__(self):
        self.rope_dim_for_mla = 4
        self.partial_rope_version = 'high'
        self.uniform_start_point = 0
        self.is_gqa2mha2mla = False
        # Create a temporary file for qk_tensor_path
        self.temp_dir = tempfile.mkdtemp()
        self.qk_tensor_path = os.path.join(self.temp_dir, 'qk_norm_rank.pt')
        # Create a dummy qk_norm_rank tensor
        qk_norm_rank = torch.randint(0, 4, (2, 2, 4))
        torch.save(qk_norm_rank, self.qk_tensor_path)

model_args = ModelArgs()
mha2mla_args = MHA2MLAArgs()

ARGS = {
    'model_args': model_args,
    'mha2mla_args': mha2mla_args,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
reorder_matrix_rows Ran
ran on a synthesized input
JT-Ushio/MHA2MLA/src/mha2mla/patching_model_load.py
code served (permissive licence) · get_code("937f754d0af3a99a")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple, ndim 2, dtype family int; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# Create a binary mask tensor
# The function uses torch.where(mask)[0] and torch.where(~mask)[0]
# So mask needs to be a boolean tensor
mask = torch.tensor([True, False, True, False])

# Test with is_cat=False (returns tuple)
ARGS = {
    "mask": mask,
    "is_cat": False
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 2, dtype family int — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
svd_low_rank_approx Ran
ran on a synthesized input
JT-Ushio/MHA2MLA/src/mha2mla/patch_func.py
code served (permissive licence) · get_code("1b387fd9635cb3ad")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned LowRankKVLinear. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Create tensors with distinct dimensions
# k_c_weight: (d_k_c, d_kv_in) - key projection weight
# k_c_bias: (d_k_c,) - key projection bias
# v_weight: (d_v, d_kv_in) - value projection weight
# v_bias: (d_v,) - value projection bias

d_k_c = 5      # output dim for key
d_v = 6        # output dim for value
d_kv_in = 7    # input dim (distinct from others)
d_kv_mid = 3   # low-rank approximation dim

k_c_weight = torch.randn(d_k_c, d_kv_in)
k_c_bias = torch.randn(d_k_c)
v_weight = torch.randn(d_v, d_kv_in)
v_bias = torch.randn(d_v)

ARGS = {
    "k_c_weight": k_c_weight,
    "k_c_bias": k_c_bias,
    "v_weight": v_weight,
    "v_bias": v_bias,
    "d_kv_mid": d_kv_mid,
    "method": "joint"
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type LowRankKVLinear — a LowRankKVLinear output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a LowRankKVLinear output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
custom_LlamaAttention_forward Not yet run
unverified (harvested, no recorded run)
JT-Ushio/MHA2MLA/src/mha2mla/patching_llama.py
code served (permissive licence) · get_code("19448606f10d10d8")
How it ran

no invocation recorded.

custom_Qwen2Attention_forward Not yet run
unverified (harvested, no recorded run)
JT-Ushio/MHA2MLA/src/mha2mla/patching_qwen2.py
code served (permissive licence) · get_code("7ac64d7242a38034")
How it ran

no invocation recorded.

custom_Qwen3Attention_forward Not yet run
unverified (harvested, no recorded run)
JT-Ushio/MHA2MLA/src/mha2mla/patching_qwen3.py
code served (permissive licence) · get_code("ccace102b231da7d")
How it ran

no invocation recorded.

custom_Qwen3MoeAttention_forward Not yet run
unverified (harvested, no recorded run)
JT-Ushio/MHA2MLA/src/mha2mla/patching_qwen3_moe.py
code served (permissive licence) · get_code("88a635fd8ae25685")
How it ran

no invocation recorded.

mha2mla_ref Not yet run
unverified (harvested, no recorded run)
JT-Ushio/MHA2MLA/src/mha2mla/mla_triton_kernel.py
code served (permissive licence) · get_code("c836c0fa19b74615")
How it ran

no invocation recorded.

Also present in other papers' code

Of 15 samples lifted from this paper's linked repositories, 15 carry a function identity and 0 do not. Of the 12 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 12 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-22.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Multi-head Latent Attention (MLA) is an innovative architecture proposed by DeepSeek, designed to ensure efficient and economical inference by significantly compressing the Key-Value (KV) cache into a latent vector. Compared to MLA, standard LLMs employing Multi-Head Attention (MHA) and its variants such as Grouped-Query Attention (GQA) exhibit significant cost disadvantages. Enabling well-trained LLMs (e.g., Llama) to rapidly adapt to MLA without pre-training from scratch is both meaningful and challenging. This paper proposes the first data-efficient fine-tuning method for transitioning from MHA to MLA (MHA2MLA), which includes two key components: for partial-RoPE, we remove RoPE from dimensions of queries and keys that contribute less to the attention scores, for lowrank approximation, we introduce joint SVD approximations based on the pre-trained parameters of keys and values. These carefully designed strategies enable MHA2MLA to recover performance using only a small fraction (0.6% to 1%) of the data, significantly reducing inference costs while seamlessly integrating with compression techniques such as KV cache quantization. For example, the KV cache size of Llama2-7B is reduced by 92.19%, with only a 1% drop in LongBench performance. 1 SVD Init.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2502.14837")
get_code_for_paper("2502.14837")
have("2502.14837")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2502.14837.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2502.14837.svg)](https://syntology.ai/paper/2502.14837)

Connect an agent — have() is free.