Layer

Grouped-query attention

×

Queries use position-aware keys to retrieve context through shared value heads.

Why

8 key-value heads. Grouped-query attention, with 8 key-value heads in every size, is one of the few changes to Llama 2’s architecture the authors list, to make inference faster and the key-value cache smaller during decoding. Llama 3 paper §3.2, p. 6

H=AVGH=AV_{\mathrm G}
Δattn=HWO\Delta_{\mathrm{attn}}=HW_O
All 14 steps
Q=xWQ{\htmlClass{vl-stream-q}{Q}}=xW_Q
K=xWK{\htmlClass{vl-stream-k}{K}}=xW_K
V=xWV{\htmlClass{vl-stream-v}{V}}=xW_V
[z2j′z2j+1′]=[cos⁡(tωj′)−sin⁡(tωj′)sin⁡(tωj′)cos⁡(tωj′)][z2jz2j+1]\begin{bmatrix}z_{2j}^{\prime}\\z_{2j+1}^{\prime}\end{bmatrix}=\begin{bmatrix}\cos(t\omega'_j)&-\sin(t\omega'_j)\\\sin(t\omega'_j)&\cos(t\omega'_j)\end{bmatrix}\begin{bmatrix}z_{2j}\\z_{2j+1}\end{bmatrix}
[z2j′z2j+1′]=[cos⁡(tωj′)−sin⁡(tωj′)sin⁡(tωj′)cos⁡(tωj′)][z2jz2j+1]\begin{bmatrix}z_{2j}^{\prime}\\z_{2j+1}^{\prime}\end{bmatrix}=\begin{bmatrix}\cos(t\omega'_j)&-\sin(t\omega'_j)\\\sin(t\omega'_j)&\cos(t\omega'_j)\end{bmatrix}\begin{bmatrix}z_{2j}\\z_{2j+1}\end{bmatrix}
KG[h]=Kr[⌊h/4⌋]{\htmlClass{vl-stream-k}{K_{\mathrm G}}}[h]={\htmlClass{vl-stream-k}{K_{\mathrm r}}}\big[\lfloor h/4\rfloor\big]
VG[h]=V[⌊h/4⌋]{\htmlClass{vl-stream-v}{V_{\mathrm G}}}[h]={\htmlClass{vl-stream-v}{V}}\big[\lfloor h/4\rfloor\big]
S=QrKGTS={\htmlClass{vl-stream-q}{Q_{\mathrm r}}}{\htmlClass{vl-stream-k}{K_{\mathrm G}^{\mathsf T}}}
Ss=S/128S_{\mathrm s}=S/\sqrt{128}
Sm=Ss+MS_{\mathrm m}=S_{\mathrm s}+{\htmlClass{vl-stream-context}{M}}
A[b,i,t,s]=exp⁡(Sm[b,i,t,s])∑u=0T−1exp⁡(Sm[b,i,t,u])A[b,i,t,s]=\frac{\exp(S_{\mathrm m}[b,i,t,s])}{\sum_{u=0}^{T-1}\exp(S_{\mathrm m}[b,i,t,u])}
H=AVGH=AV_{\mathrm G}
H=reshape⁡(H)H=\operatorname{reshape}(H)
Δattn=HWO\Delta_{\mathrm{attn}}=HW_O
in
xattnx_{\mathrm{attn}} [B batch, T positions, 4096 d]RR [T positions, 64 pairs]MM [T queries, T keys]
out
Δattn\Delta_{\mathrm{attn}} [B batch, T positions, 4096 d]
Parameters41,943,040 × 32 layers

41,943,040 parameters per instance, across its learned components

ComponentCalculationParameters
Query projection4,096 × 4,09616,777,216
Key projection4,096 × (8 × 128)4,194,304
Value projection4,096 × (8 × 128)4,194,304
Output projection4,096 × 4,09616,777,216
Per-instance total41,943,040

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

Not checked against a checkpoint.

KV cache

KV cache per token · all layers

Llama 3.1 8B · 16-bit128 KiB
MHA (32 K/V heads) · 16-bit512 KiB

2 (K, V) × 32 layers × 8 heads × 128 × 2 bytes. At the full 131,072 tokens: 16 GiB per sequence (MHA: 64 GiB).

Grouping cuts WK,WVW_K, W_V and the cache 4×; the score and value products still run over 32 heads.

model.py 129–177generation.py 105–108
Sources

In codeself.attention(self.attention_norm(x), start_pos, freqs_cis, mask)

Open pinned code ↗

Direct evidence

Meta's Llama 3.1 8B base catalogue entry supplies dimensions, head counts, the vocabulary (LLAMA3_VOCAB_SIZE, line 19), MLP rounding, epsilon, rope_theta and use_scaled_rope: True.

sku_list.py 19–248 ↗ · meta-llama/llama-models @ 0e0b8c519242

Excerpt
LLAMA3_VOCAB_SIZE = 128256

… lines 20–230 omitted …

        Model(
            core_model_id=CoreModelId.llama3_1_8b,
            description="Llama 3.1 8b model",
            huggingface_repo="meta-llama/Llama-3.1-8B",
            arch_args={
                "dim": 4096,
                "n_layers": 32,
                "n_heads": 32,
                "n_kv_heads": 8,
                "vocab_size": LLAMA3_VOCAB_SIZE,
                "ffn_dim_multiplier": 1.3,
                "multiple_of": 1024,
                "norm_eps": 1e-05,
                "rope_theta": 500000.0,
                "use_scaled_rope": True,
            },
            pth_file_count=1,
        ),

Separate bias-free Q/K/V projections use configured query and KV head widths, then reshape into heads.

model.py 93–160 ↗ · meta-llama/llama3 @ a0940f9cf706

Excerpt
        self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
        model_parallel_size = fs_init.get_model_parallel_world_size()
        self.n_local_heads = args.n_heads // model_parallel_size
        self.n_local_kv_heads = self.n_kv_heads // model_parallel_size
        self.n_rep = self.n_local_heads // self.n_local_kv_heads
        self.head_dim = args.dim // args.n_heads

        self.wq = ColumnParallelLinear(
            args.dim,
            args.n_heads * self.head_dim,
            bias=False,
            gather_output=False,
            init_method=lambda x: x,
        )
        self.wk = ColumnParallelLinear(
            args.dim,
            self.n_kv_heads * self.head_dim,
            bias=False,
            gather_output=False,
            init_method=lambda x: x,
        )
        self.wv = ColumnParallelLinear(
            args.dim,
            self.n_kv_heads * self.head_dim,
            bias=False,
            gather_output=False,
            init_method=lambda x: x,
        )

… lines 121–152 omitted …

        bsz, seqlen, _ = x.shape
        xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)

        xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
        xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
        xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)

        xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)

Complex-pair rotations apply to queries and keys, with their original dtype restored.

model.py 65–160 ↗ · meta-llama/llama3 @ a0940f9cf706

Excerpt
def apply_rotary_emb(
    xq: torch.Tensor,
    xk: torch.Tensor,
    freqs_cis: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
    xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
    xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
    freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
    xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
    xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
    return xq_out.type_as(xq), xk_out.type_as(xk)

… lines 76–155 omitted …

        xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
        xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
        xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)

        xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)

Each KV head serves a group of query heads; the reference implementation expands KV heads before score/value multiplication.

model.py 78–183 ↗ · meta-llama/llama3 @ a0940f9cf706

Excerpt
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
    """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
    bs, slen, n_kv_heads, head_dim = x.shape
    if n_rep == 1:
        return x
    return (
        x[:, :, :, None, :]
        .expand(bs, slen, n_kv_heads, n_rep, head_dim)
        .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
    )

… lines 88–92 omitted …

        self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
        model_parallel_size = fs_init.get_model_parallel_world_size()
        self.n_local_heads = args.n_heads // model_parallel_size
        self.n_local_kv_heads = self.n_kv_heads // model_parallel_size
        self.n_rep = self.n_local_heads // self.n_local_kv_heads
        self.head_dim = args.dim // args.n_heads

… lines 99–170 omitted …

        # repeat k/v heads if n_kv_heads < n_heads
        keys = repeat_kv(
            keys, self.n_rep
        )  # (bs, cache_len + seqlen, n_local_heads, head_dim)
        values = repeat_kv(
            values, self.n_rep
        )  # (bs, cache_len + seqlen, n_local_heads, head_dim)

        xq = xq.transpose(1, 2)  # (bs, n_local_heads, seqlen, head_dim)
        keys = keys.transpose(1, 2)  # (bs, n_local_heads, cache_len + seqlen, head_dim)
        values = values.transpose(
            1, 2
        )  # (bs, n_local_heads, cache_len + seqlen, head_dim)

Queries multiply transposed keys, scores are divided by the square root of head width, a causal mask is added, and softmax runs over key positions.

model.py 179–296 ↗ · meta-llama/llama3 @ a0940f9cf706

Excerpt
        xq = xq.transpose(1, 2)  # (bs, n_local_heads, seqlen, head_dim)
        keys = keys.transpose(1, 2)  # (bs, n_local_heads, cache_len + seqlen, head_dim)
        values = values.transpose(
            1, 2
        )  # (bs, n_local_heads, cache_len + seqlen, head_dim)
        scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim)
        if mask is not None:
            scores = scores + mask  # (bs, n_local_heads, seqlen, cache_len + seqlen)
        scores = F.softmax(scores.float(), dim=-1).type_as(xq)

… lines 188–283 omitted …

        mask = None
        if seqlen > 1:
            mask = torch.full((seqlen, seqlen), float("-inf"), device=tokens.device)

            mask = torch.triu(mask, diagonal=1)

            # When performing key-value caching, we compute the attention scores
            # only for the new sequence. Thus, the matrix of scores is of size
            # (seqlen, cache_len + seqlen), and the only masked entries are (i, j) for
            # j > cache_len + i, since row i corresponds to token cache_len + i.
            mask = torch.hstack(
                [torch.zeros((seqlen, start_pos), device=tokens.device), mask]
            ).type_as(h)

Normalized attention weights multiply values; head outputs are merged and passed through a learned bias-free output projection.

model.py 121–190 ↗ · meta-llama/llama3 @ a0940f9cf706

Excerpt
        self.wo = RowParallelLinear(
            args.n_heads * self.head_dim,
            args.dim,
            bias=False,
            input_is_parallel=True,
            init_method=lambda x: x,
        )

… lines 128–183 omitted …

        scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim)
        if mask is not None:
            scores = scores + mask  # (bs, n_local_heads, seqlen, cache_len + seqlen)
        scores = F.softmax(scores.float(), dim=-1).type_as(xq)
        output = torch.matmul(scores, values)  # (bs, n_local_heads, seqlen, head_dim)
        output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
        return self.wo(output)

Attention receives attention_norm(x) and its update is added to x; the MLP receives ffn_norm(h) and its update is added to h.

model.py 236–248 ↗ · meta-llama/llama3 @ a0940f9cf706

Excerpt
        self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
        self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)

    def forward(
        self,
        x: torch.Tensor,
        start_pos: int,
        freqs_cis: torch.Tensor,
        mask: Optional[torch.Tensor],
    ):
        h = x + self.attention(self.attention_norm(x), start_pos, freqs_cis, mask)
        out = h + self.feed_forward(self.ffn_norm(h))
        return out