Llama 3

Size
Published
Meta · Apr 2024
Line
Dense decoder
View
Architecture
Source

meta‑llama/llama3 @ a0940f9, configuration meta‑llama/llama‑models @ 0e0b8c5 · checkpoint, tokenizer and tensors not verifiedHow to read

Grouped-query attention

32 independent transformer blocks › Attention

Apply causal mask

×

no parametersscores + mask

Exclude future key positions from each query’s attention weights.

Sm=Ss+M{\htmlData{light=causal}{S_{\mathrm m}}}={\htmlData{light=scale}{S_{\mathrm s}}}+{\htmlData{light=attention-mask}{{\htmlClass{vl-stream-context}{M}}}}
in
SsS_{\mathrm s} [B batch, 32 q heads, T queries, T keys]MM [T queries, T keys]
out
SmS_{\mathrm m} [B batch, 32 q heads, T queries, T keys]

Added only when a mask is passed; with T = 1 the step is skipped (model.py 185–186, 285).

Explanation

Masked entries are −∞-\infty, so softmax gives them weight zero.

Codemodel.py 185–186, 284–296
model.py 185–186
        if mask is not None:
            scores = scores + mask  # (bs, n_local_heads, seqlen, cache_len + seqlen)
model.py 284–296
        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)
Sources1

Direct evidence

The model constructs an upper-triangular negative-infinity mask; attention adds it to the scaled scores.

attn-mask · meta-llama/llama3 / llama/model.py
Pinned revision a0940f9cf706 ↗ · lines 185–296

Read code excerpt
        if mask is not None:
            scores = scores + mask  # (bs, n_local_heads, seqlen, cache_len + seqlen)

… lines 187–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)