Skip to main content

MATH 345: Linear Algebra and Optimization

Section B.13 Boolean Masks, Copying, and Attention Helpers

This optional section helps you read the array-manipulation code used in the optional attention material.
S = np.array([[1.0, 2.0, 3.0],
              [4.0, 5.0, 6.0],
              [7.0, 8.0, 9.0]])

mask = np.triu(np.ones_like(S), k=1).astype(bool)

S_masked = S.copy()
S_masked[mask] = -1e9
def softmax_rows(S):
    S_shifted = S - np.max(S, axis=1, keepdims=True)
    e = np.exp(S_shifted)
    return e / e.sum(axis=1, keepdims=True)
grad_W = np.outer(g, h)

Matching ones.

np.ones_like(S)
Read as. Ones with the same shape as S.
Shape/return. An array.
Used for. Mask construction.

Upper triangle.

np.triu(..., k=1)
Read as. Entries above the diagonal.
Shape/return. An array.
Used for. Causal mask.

Boolean conversion.

.astype(bool)
Read as. Convert to True/False.
Shape/return. A Boolean array.
Used for. Mask indexing.

Independent copy.

S.copy()
Read as. Make an independent copy.
Shape/return. An array.
Used for. Safe modification.

Mask assignment.

S_masked[mask] = -1e9
Read as. Change selected entries.
Shape/return. A modified array.
Used for. Masked attention scores.

Row maximum.

np.max(S, axis=1, keepdims=True)
Read as. Row maximum.
Shape/return. A column-shaped array.
Used for. Stable softmax.

Exponential.

np.exp(S_shifted)
Read as. Entry-by-entry exponential.
Shape/return. An array.
Used for. Softmax.

Row normalization.

e / e.sum(axis=1, keepdims=True)
Read as. Row normalization.
Shape/return. An array with row sums 1.
Used for. Attention weights.

Outer product.

np.outer(g, h)
Read as. Outer product.
Shape/return. A matrix.
Used for. Rank-one update.

Warning B.13.1. Large negative mask values are numerical placeholders.

The value -1e9 is a numerical stand-in for a very large negative score in the optional attention code.