Causal mask

×

Position-derived mask shared by the attention computation in all layers.

shape
MM [T queries, T keys]
Sources

Contextual evidence

The model builds the causal mask only when sequence length exceeds one and passes it into every layer.

model.py 284–300 ↗ · meta-llama/llama3 @ a0940f9cf706

Excerpt
        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)

        for layer in self.layers:
            h = layer(h, start_pos, freqs_cis, mask)
        h = self.norm(h)