Multi-head latent attention

Causal attention

×

Attend over current and earlier positions with 128 heads and project the result to the model width.

O=AVO=AV
Δattn=oWO\Delta_{\mathrm{attn}}=oW_{O}
All 8 steps
S=QKTS=QK^{\mathsf T}
S′=S⋅m2192S'=S\cdot\frac{m^2}{\sqrt{192}}
m=1+0.1ln⁡40m=1+0.1\ln 40
S~=S′+M\tilde S=S'+{\htmlClass{vl-stream-context}{M}}
A[b,i,t,s]=exp⁡(S~[b,i,t,s])∑u=0T−1exp⁡(S~[b,i,t,u])A[b,i,t,s]=\frac{\exp(\tilde S[b,i,t,s])}{\sum_{u=0}^{T-1}\exp(\tilde S[b,i,t,u])}
Mix and project:\text{Mix and project:}
O=AVO=AV
o=reshape⁡(O)o=\operatorname{reshape}(O)
Δattn=oWO\Delta_{\mathrm{attn}}=oW_{O}
in
QQ [B batch, 128 heads, T positions, 192 content + rotary]MM [T queries, T keys]
out
Δattn\Delta_{\mathrm{attn}} [B batch, T positions, 7168 d]
Parameters117,440,512 × 58 layers

117,440,512 parameters per instance, across its learned components

ComponentParameters
Mix and project117,440,512

One in each of the 58 MoE layers, each with its own weights.

Explanation

These cards give the eager class’s code, DeepseekV3Attention (modeling_deepseek.py 815–851); config._attn_implementation chooses between it and DeepseekV3FlashAttention2 (860, 1136–1149).

Sources

In codeDeepseekV3Attention.forward · 815–851

Open pinned code ↗

Direct evidence

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 798–839 ↗ · deepseek-ai/DeepSeek-V3 @ e815299b0bcb

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)

Head outputs are flattened and projected back to the model width.

modeling_deepseek.py 847–851 ↗ · deepseek-ai/DeepSeek-V3 @ e815299b0bcb

Excerpt
        attn_output = attn_output.transpose(1, 2).contiguous()

        attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)

        attn_output = self.o_proj(attn_output)