Build a causal mask that also blocks attention across packed documents

Why it matters Packed training rows for LLM fine-tuning need document-aware masks to avoid cross-example contamination.

When several short documents are packed into one training row, a plain causal mask lets tokens attend to earlier documents, leaking unrelated context. The fix keeps attention causal AND inside the same document.

Write packed_causal_mask(doc_ids) where doc_ids is a 1D int array of length T giving the document of each position (documents are contiguous). Return a (T, T) bool array M with M[i, j] True when position i may attend to position j: j <= i and doc_ids[j] == doc_ids[i].

Signaturedef packed_causal_mask(doc_ids)

Example

packed_causal_mask([0, 0, 1]) is [[True, False, False], [True, True, False], [False, False, True]].

Understand the idea

Attention masks say which keys each query may look at. A causal mask allows key j for query i only when j <= i, so a token never sees the future. With packed documents we also need j to be in the same document as i, otherwise document 2 can read document 1.

Worked example: doc_ids [0, 0, 1]. Causal allows (0,0), (1,0), (1,1), (2,0), (2,1), (2,2). Same-document allows pairs within {0, 1} and {2}. Both together: (0,0), (1,0), (1,1), (2,2). Position 2 only attends to itself.

Rule: M[i, j] = (j <= i) and (doc[i] == doc[j]). In NumPy: (pos[None, :] <= pos[:, None]) & (d[:, None] == d[None, :]). The result is block diagonal with a lower triangle in each block.

Sequence packing for fine-tuning and variable-length attention kernels rely on this mask.

Shapes and data flow

doc_ids (T,) -> causal (T, T) & same (T, T) -> M (T, T)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplepacked_causal_mask([0, 0, 1])
  • Sample 2: three documentspacked_causal_mask([5, 5, 5, 7, 9, 9])
  • Test 3: one documentpacked_causal_mask([2, 2, 2])
  • Test 4: allowed pairsint(packed_causal_mask([0, 1, 1, 1, 2, 2]).sum())