Implement one causal scaled-dot-product attention head.

Instruction: Using Python and NumPy, implement attention for finite nonempty 2D Q, K and V. Q and K have shape (tokens, key_dim); V has shape (tokens, value_dim). Use a causal mask and stable softmax. Test that changing a future token cannot alter an earlier output. This exercise does not ask for a full trainable transformer.

Context: Implement the numerical core of a decoder attention head with explicit shapes and a causal masking test.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

Scores are QKᵀ/√d. Row i can attend only to columns j≤i. Subtracting the row maximum before exponentiation improves numerical stability.

```python import numpy as np...

Related Questions