---
title: Scaled dot-product attention with a mask
url: https://gurkanozkan.ai/learn/coding/mle-scaled-dot-product-attention-with-a-mask-13/
markdown: https://gurkanozkan.ai/learn/coding/mle-scaled-dot-product-attention-with-a-mask-13.md
kind: coding
difficulty: Medium
topics:
  - Transformers
  - Attention
  - NumPy
json: https://gurkanozkan.ai/api/learn/coding/mle-scaled-dot-product-attention-with-a-mask-13.json
robots: noindex
---

# Scaled dot-product attention with a mask

Shapes: `Q` (Tq, d), `K` (Tk, d), `V` (Tk, dv). Compute `softmax(QKᵀ/√d)·V`. `mask` is an optional boolean (Tq, Tk) array where `True` means "may attend"; masked positions must get weight exactly 0. Assume each row has at least one `True`. Return `(output, weights)`.

## Signature

```python
def attention(Q, K, V, mask=None) -> tuple[np.ndarray, np.ndarray]: ...
```

## Examples

Each call and the value it should give.

```python
>>> close(attention([[0.0, 0.0]], [[1.0, 0.0],[0.0, 1.0]], [[1.0, 2.0],[3.0, 4.0]]), ([[2.0, 3.0]], [[0.5, 0.5]]))
True

>>> close(attention([[1.0, 0.0]], [[1.0, 0.0],[0.0, 1.0]], [[1.0],[0.0]]), ([[0.669762]], [[0.669762, 0.330238]]))
True
```

## Hints

1. Scale Q*K^T by 1/sqrt(d).
2. Mask positions to -inf before the softmax, then max-subtract for stability.
3. Weights rows must sum to 1; return (output, weights).

## Reference solution

```python
import math
import numpy as np

def attention(Q, K, V, mask=None):
    Q = np.asarray(Q, float); K = np.asarray(K, float); V = np.asarray(V, float)
    s = Q @ K.T / math.sqrt(Q.shape[1])
    if mask is not None:
        s = np.where(np.asarray(mask, bool), s, -np.inf)
    s = s - s.max(axis=1, keepdims=True)
    w = np.exp(s)
    w = w / w.sum(axis=1, keepdims=True)
    return w @ V, w
```

## What a strong solution covers

- Correct scaling.
- Masks with −inf (or a large negative) *before* the softmax, with max-subtraction.
- Weights rows sum to 1.
- Discusses O(T²) memory and the causal mask construction.

## Common mistakes

- multiplying weights by the mask after the softmax (rows no longer sum to 1)
- scaling by d instead of √d.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
