Build a Lower-Triangular Causal Attention Mask

Basics
BasicsTransformersAttentionOpenAIAnthropicGoogle

Problem

Implement causal_mask(seq_len) returning a (seq_len, seq_len) lower-triangular integer NumPy array where entry (i, j) is 1 if query token i is allowed to attend to key token j (j <= i), and 0 for future tokens (j > i).

Why It Matters: Causal (autoregressive) masking is what prevents decoder-only LLMs like GPT, Gemini, and Llama from 'cheating' by peeking at future tokens during parallel training.

Function Signature

import numpy as np

def causal_mask(seq_len: int) -> np.ndarray:
    """Return a (seq_len, seq_len) lower-triangular 0/1 causal attention mask."""

Sample Input & Output

Example 1: Sequence Length 3

Input:

seq_len = 3

Expected Output:

array([[1, 0, 0],
       [1, 1, 0],
       [1, 1, 1]])

Explanation: Token 0 sees only [0]; token 1 sees [0, 1]; token 2 sees [0, 1, 2].

Example 2: Single-Token Sequence (seq_len = 1)

Input:

seq_len = 1

Expected Output:

array([[1]])

Explanation: A 1-token sequence still returns a 2D (1, 1) integer matrix with a single 1.

Constraints & Edge Cases

  • Return a (seq_len, seq_len) integer matrix with 1 on and below the diagonal and 0 above.
  • Output dtype should be integer (int) with exact shape (seq_len, seq_len).
  • np.tril(np.ones((seq_len, seq_len), dtype=int)) builds the mask in one vectorized call.

Constraints & Evaluation Criteria

  • Return a `(seq_len, seq_len)` integer matrix with `1` on and below the diagonal and `0` above.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
seq_len = 3
Expected Output / Criteria
3x3 lower-triangular 0/1