Multi-head latent attention

Values

×

64 value heads of 128 features.

shape
VV [B batch, 64 heads, 1 position, 128 value]
Sources

Contextual evidence from Value heads

MLA owns a query down-projection, query RMSNorm and up-projection, a joint key–value down-projection that also emits the shared rotary key, a latent RMSNorm, a key–value up-projection and an output projection.

modeling_deepseek.py 665–691 ↗ · moonshotai/Kimi-K2.5 @ 4d01dfe0332d

Excerpt
            self.q_a_proj = nn.Linear(self.hidden_size,
                                      config.q_lora_rank,
                                      bias=config.attention_bias)
            self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
            self.q_b_proj = nn.Linear(config.q_lora_rank,
                                      self.num_heads * self.q_head_dim,
                                      bias=False)

        self.kv_a_proj_with_mqa = nn.Linear(
            self.hidden_size,
            config.kv_lora_rank + config.qk_rope_head_dim,
            bias=config.attention_bias,
        )
        self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank)
        self.kv_b_proj = nn.Linear(
            config.kv_lora_rank,
            self.num_heads *
            (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
            bias=False,
        )

        self.o_proj = nn.Linear(
            self.num_heads * self.v_head_dim,
            self.hidden_size,
            bias=config.attention_bias,
        )
        self._init_rope()

The rotary parts are rotated; each head’s query and key join their non-rotated and rotated parts, the key’s rotated part being the shared rotary key; scores are scaled, masked by the causal mask, normalized and used to mix values.

modeling_deepseek.py 794–836 ↗ · moonshotai/Kimi-K2.5 @ 4d01dfe0332d

Excerpt
        cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)

        q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)

        query_states = k_pe.new_empty(bsz, self.num_heads, q_len,
                                      self.q_head_dim)
        query_states[:, :, :, :self.qk_nope_head_dim] = q_nope
        query_states[:, :, :, self.qk_nope_head_dim:] = q_pe

        key_states = k_pe.new_empty(bsz, self.num_heads, q_len,
                                    self.q_head_dim)
        key_states[:, :, :, :self.qk_nope_head_dim] = k_nope
        key_states[:, :, :, self.qk_nope_head_dim:] = k_pe
        if past_key_value is not None:
            cache_kwargs = {"sin": sin, "cos": cos}  # Specific to RoPE models
            key_states, value_states = past_key_value.update(
                key_states, value_states, self.layer_idx, cache_kwargs)

        attn_weights = (
            torch.matmul(query_states, key_states.transpose(2, 3)) *
            self.softmax_scale)

        if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
            raise ValueError(
                f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
                f" {attn_weights.size()}")
        assert attention_mask is not None
        if attention_mask is not None:
            if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
                raise ValueError(
                    f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
                )
            attn_weights = attn_weights + attention_mask

        # upcast attention to fp32
        attn_weights = nn.functional.softmax(attn_weights,
                                             dim=-1,
                                             dtype=torch.float32).to(
                                                 query_states.dtype)
        attn_weights = nn.functional.dropout(attn_weights,
                                             p=self.attention_dropout,
                                             training=self.training)
        attn_output = torch.matmul(attn_weights, value_states)

Contextual evidence from KV cache

With a cache, the cached length is added to this call’s (get_usable_length, which the file defines for newer transformers versions, returns the cache’s length unless a bounded cache would overflow), the rebuilt and rotated keys and the values are handed to the cache object, which returns every cached key and value so far, and the scores cover all of them.

modeling_deepseek.py 84–819 ↗ · moonshotai/Kimi-K2.5 @ 4d01dfe0332d

Excerpt
def get_usable_length(past_key_value,
                      new_seq_length: int,
                      layer_idx: Optional[int] = 0) -> int:
    max_length = past_key_value.get_max_cache_shape()
    previous_seq_length = past_key_value.get_seq_length(layer_idx)
    if max_length is not None and max_length > 0 and previous_seq_length + new_seq_length > max_length:
        return max_length - new_seq_length
    return previous_seq_length

… lines 92–784 omitted …

        kv_seq_len = value_states.shape[-2]
        if past_key_value is not None:
            if self.layer_idx is None:
                raise ValueError(
                    f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
                    "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
                    "with a layer index.")
            kv_seq_len += get_usable_length(past_key_value, kv_seq_len,
                                            self.layer_idx)
        cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)

… lines 796–806 omitted …

        if past_key_value is not None:
            cache_kwargs = {"sin": sin, "cos": cos}  # Specific to RoPE models
            key_states, value_states = past_key_value.update(
                key_states, value_states, self.layer_idx, cache_kwargs)

        attn_weights = (
            torch.matmul(query_states, key_states.transpose(2, 3)) *
            self.softmax_scale)

        if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
            raise ValueError(
                f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
                f" {attn_weights.size()}")

The joint down-projection yields the key–value latent and one rotary key shared by all heads; the latent is normalized and up-projected into per-head content keys and values.

modeling_deepseek.py 775–784 ↗ · moonshotai/Kimi-K2.5 @ 4d01dfe0332d

Excerpt
        compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
        compressed_kv, k_pe = torch.split(
            compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
        k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
        kv = (self.kv_b_proj(self.kv_a_layernorm(compressed_kv)).view(
            bsz, q_len, self.num_heads,
            self.qk_nope_head_dim + self.v_head_dim).transpose(1, 2))

        k_nope, value_states = torch.split(
            kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)

The language model’s configuration (text_config): the DeepSeek-V3 architecture, width, 61 layers of which 1 dense, 64 heads, 384 routed experts and one shared, routing (sigmoid scores, one expert group, top-8, route scale 2.827), MLA ranks and head widths, vocabulary, 262,144 positions and YaRN RoPE (factor 64 over 4,096 original positions, β_fast 32, β_slow 1).

config.json 17–167 ↗ · moonshotai/Kimi-K2.5 @ 4d01dfe0332d

Excerpt
  "text_config": {
    "_name_or_path": "",
    "add_cross_attention": false,
    "architectures": [
      "DeepseekV3ForCausalLM"
    ],
    "attention_bias": false,
    "attention_dropout": 0.0,
    "auto_map": {
      "AutoConfig": "configuration_deepseek.DeepseekV3Config",
      "AutoModel": "modeling_deepseek.DeepseekV3Model",
      "AutoModelForCausalLM": "modeling_deepseek.DeepseekV3ForCausalLM"
    },
    "aux_loss_alpha": 0.001,
    "bad_words_ids": null,
    "begin_suppress_tokens": null,
    "bos_token_id": 163584,
    "chunk_size_feed_forward": 0,
    "cross_attention_hidden_size": null,
    "decoder_start_token_id": null,
    "diversity_penalty": 0.0,
    "do_sample": false,
    "dtype": "bfloat16",
    "early_stopping": false,
    "encoder_no_repeat_ngram_size": 0,
    "eos_token_id": 163585,
    "ep_size": 1,
    "exponential_decay_length_penalty": null,
    "finetuning_task": null,
    "first_k_dense_replace": 1,
    "forced_bos_token_id": null,
    "forced_eos_token_id": null,
    "hidden_act": "silu",
    "hidden_size": 7168,
    "id2label": {
      "0": "LABEL_0",
      "1": "LABEL_1"
    },
    "initializer_range": 0.02,
    "intermediate_size": 18432,
    "is_decoder": false,
    "is_encoder_decoder": false,
    "kv_lora_rank": 512,
    "label2id": {
      "LABEL_0": 0,
      "LABEL_1": 1
    },
    "length_penalty": 1.0,
    "max_length": 20,
    "max_position_embeddings": 262144,
    "min_length": 0,
    "model_type": "kimi_k2",
    "moe_intermediate_size": 2048,
    "moe_layer_freq": 1,
    "n_group": 1,
    "n_routed_experts": 384,
    "n_shared_experts": 1,
    "no_repeat_ngram_size": 0,
    "norm_topk_prob": true,
    "num_attention_heads": 64,
    "num_beam_groups": 1,
    "num_beams": 1,
    "num_experts_per_tok": 8,
    "num_hidden_layers": 61,
    "num_key_value_heads": 64,
    "num_nextn_predict_layers": 0,
    "num_return_sequences": 1,
    "output_attentions": false,
    "output_hidden_states": false,
    "output_scores": false,
    "pad_token_id": 163839,
    "prefix": null,
    "pretraining_tp": 1,
    "problem_type": null,
    "pruned_heads": {},
    "q_lora_rank": 1536,
    "qk_nope_head_dim": 128,
    "qk_rope_head_dim": 64,
    "quantization_config": {
      "config_groups": {
        "group_0": {
          "input_activations": null,
          "output_activations": null,
          "targets": [
            "Linear"
          ],
          "weights": {
            "actorder": null,
            "block_structure": null,
            "dynamic": false,
            "group_size": 32,
            "num_bits": 4,
            "observer": "minmax",
            "observer_kwargs": {},
            "strategy": "group",
            "symmetric": true,
            "type": "int"
          }
        }
      },
      "format": "pack-quantized",
      "ignore": [
        "re:.*self_attn.*",
        "re:.*shared_experts.*",
        "re:.*mlp\\.(gate|up|gate_up|down)_proj.*",
        "re:.*lm_head.*",
        "re:vision_tower.*",
        "re:mm_projector.*"
      ],
      "kv_cache_scheme": null,
      "quant_method": "compressed-tensors",
      "quantization_status": "compressed"
    },
    "remove_invalid_values": false,
    "repetition_penalty": 1.0,
    "return_dict": true,
    "return_dict_in_generate": false,
    "rms_norm_eps": 1e-05,
    "rope_scaling": {
      "beta_fast": 32.0,
      "beta_slow": 1.0,
      "factor": 64.0,
      "mscale": 1.0,
      "mscale_all_dim": 1.0,
      "original_max_position_embeddings": 4096,
      "type": "yarn"
    },
    "rope_theta": 50000.0,
    "routed_scaling_factor": 2.827,
    "scoring_func": "sigmoid",
    "sep_token_id": null,
    "seq_aux": true,
    "suppress_tokens": null,
    "task_specific_params": null,
    "temperature": 1.0,
    "tf_legacy_loss": false,
    "tie_encoder_decoder": false,
    "tie_word_embeddings": false,
    "tokenizer_class": null,
    "top_k": 50,
    "top_p": 1.0,
    "topk_group": 1,
    "topk_method": "noaux_tc",
    "torchscript": false,
    "transformers_version": "4.56.2",
    "typical_p": 1.0,
    "use_bfloat16": false,
    "use_cache": true,
    "v_head_dim": 128,
    "vocab_size": 163840
  },