Skip to content
mlmentorship

Causal Attention

Compute one attention head where each token can read only itself and earlier tokens.

Published · 12 min read ·Role-specific ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Causal Attention

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. Float64 arrays query and key with shape (n, d), and value with shape (n, dv). Output. Return an (n, dv) array containing one scaled dot-product attention result per query position. Scores use dot products divided by the square root of d, normalized over permitted keys. Rules. Query position i may use positions 0 through i, including itself, but no later position. Require positive n and d, aligned sequence positions, and representable finite scores. Preserve the inputs. Repeated values and positions' content are allowed. Example. With two all-zero query/key rows and value rows [[2], [6]], return [[2], [4]]. The first position sees only 2; the second averages both values because their scores are equal.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Form scaled query-key scores, mask the strict upper triangle before softmax, then use prefix-only weights to mix values.

Problem trace

Future positions receive exactly zero attention weight

Worked example: future positions receive zero weightThe current query mixes information from earlier and current positions. Its future input is present, but its path is closed. Make that future value ten times larger: the blocked path still adds nothing, so the output stays unchanged.The current position cannot read thefutureEarlier1readableCurrent2readableFuture100blockedCurrent output: 1.6Change only the future inputFuture 1001.6Future 10001.6Same output; the future path staysclosed
Read it this way: The current query mixes information from earlier and current positions. Its future input is present, but its path is closed. Make that future value ten times larger: the blocked path still adds nothing, so the output stays unchanged. If the future scalar grows from one hundred to one thousand, does its masked contribution change?
Full interview answer 12 min read
Reading depth

Compute attention outputs for a sequence while preventing every position from using information from future positions.

Problem

Input. Float64 arrays query and key with shape (n, d), and value with shape (n, dv).

Output. Return an (n, dv) array containing one scaled dot-product attention result per query position. Scores use dot products divided by the square root of d, normalized over permitted keys.

Rules. Query position i may use positions 0 through i, including itself, but no later position. Require positive n and d, aligned sequence positions, and representable finite scores. Preserve the inputs. Repeated values and positions’ content are allowed.

Example. With two all-zero query/key rows and value rows [[2], [6]], return [[2], [4]]. The first position sees only 2; the second averages both values because their scores are equal.

Picture

With Q=K=[[1,0],[0,1]], scores are the identity divided by . Query zero sees only key zero; query one sees both keys. For V=[[10,0],[0,20]], output zero is [10,0]; output one is approximately [3.3024,13.3952].

Problem trace

Separate coded fixture: mask scores before normalization and value mixing

Input and goalCompute one attention head where each token can read only itself and earlier tokens.
Multiply queries by keysUse Q=K=[[1,0],[0,1]] and V=[[10,0],[0,20]]. QK^T is the 2 by 2 identity score matrix.
1001
axesquery rows x key rows
axes
query rows x key rows
column 0 / row 0
1
column 1 / row 0
0

Recognize it
Use it when each sequence position may aggregate only its own and earlier value rows, requiring future key positions to receive exactly zero normalized weight.
Keep true
Attention row i contains scores for query i against every key; after masking and softmax, entries j>i are zero and allowed prefix weights j<=i sum to one.
Reuse it
For constrained attention, encode allowed information flow as a score-space mask before normalization so forbidden positions receive zero mass, then mix values with the resulting row-stochastic weights.
Use Q=K=[[1,0],[0,1]] and V=[[10,0],[0,20]]. QK^T is the 2 by 2 identity score matrix. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can query 0 not use V1 even if that future key would have a high score?
Reference drawing

Problem trace

Future positions receive exactly zero attention weight

Worked example: future positions receive zero weightThe current query mixes information from earlier and current positions. Its future input is present, but its path is closed. Make that future value ten times larger: the blocked path still adds nothing, so the output stays unchanged.The current position cannot read thefutureEarlier1readableCurrent2readableFuture100blockedCurrent output: 1.6Change only the future inputFuture 1001.6Future 10001.6Same output; the future path staysclosed
Execution trace
Input and goalCompute one attention head where each token can read only itself and earlier tokens.
Multiply queries by keysUse Q=K=[[1,0],[0,1]] and V=[[10,0],[0,20]]. QK^T is the 2 by 2 identity score matrix.
1001
axesquery rows x key rows
axes
query rows x key rows
column 0 / row 0
1
column 1 / row 0
0

Recognize it
Use it when each sequence position may aggregate only its own and earlier value rows, requiring future key positions to receive exactly zero normalized weight.
Keep true
Attention row i contains scores for query i against every key; after masking and softmax, entries j>i are zero and allowed prefix weights j<=i sum to one.
Reuse it
For constrained attention, encode allowed information flow as a score-space mask before normalization so forbidden positions receive zero mass, then mix values with the resulting row-stochastic weights.
Use Q=K=[[1,0],[0,1]] and V=[[10,0],[0,20]]. QK^T is the 2 by 2 identity score matrix. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can query 0 not use V1 even if that future key would have a high score?
Read it this way: The current query mixes information from earlier and current positions. Its future input is present, but its path is closed. Make that future value ten times larger: the blocked path still adds nothing, so the output stays unchanged. If the future scalar grows from one hundred to one thousand, does its masked contribution change?

The attention owner explains the weighted mixture. Here the extra contract is visibility: a strict upper triangle contributes no exponential mass before rowwise normalization.

Code

import numpy as np

def causal_attention(
   query: np.ndarray, key: np.ndarray, value: np.ndarray
) -> np.ndarray:
   scores = query @ key.T / np.sqrt(query.shape[-1])
   future = np.triu(np.ones(scores.shape, dtype=bool), k=1)
   scores[future] = -np.inf
   exponentials = np.exp(scores - np.max(scores, axis=-1, keepdims=True))
   weights = exponentials / np.sum(exponentials, axis=-1, keepdims=True)
   return weights @ value

Cost: arithmetic and score/weight workspace, plus output.

Change the Requirement

Add Padding or Explicit Visibility

New task: Accept a Boolean (query_rows,key_rows) visibility mask.

Picture and change: Compose padding and causality before softmax; reject rows without any allowed key.

Code: Retain positive feature width and finite representable scores.

def attention_with_mask(query, key, value, allowed):
   scores = query @ key.T / np.sqrt(query.shape[-1])
   allowed = np.asarray(allowed, dtype=bool)
   if allowed.shape != scores.shape or np.any(~allowed.any(axis=-1)):
      raise ValueError("each query needs a matching nonempty visibility row")
   scores = np.where(allowed, scores, -np.inf)
   exponentials = np.exp(scores - scores.max(axis=-1, keepdims=True))
   weights = exponentials / exponentials.sum(axis=-1, keepdims=True)
   return weights @ value

Check: For the example, mask [[True,False],[True,False]] produces [10,0] for both queries.

Use when: Padding removes otherwise visible keys. Multiplying weights by a mask afterward does not renormalize the distribution.

Decode Against Cached Positions

New task: Permit rectangular query/key arrays with explicit integer positions.

Picture and change: A key is visible when its absolute position does not exceed the query position.

Code: Position-vector lengths must match their corresponding arrays.

def cached_causal_attention(query, key, value, query_positions, key_positions):
   allowed = np.asarray(key_positions)[None, :] <= np.asarray(query_positions)[:, None]
   return attention_with_mask(query, key, value, allowed)

Check: One query at position 2 can see cached keys at positions 0,1; both receive nonzero weights.

Use when: Local row zero is not absolute sequence position zero. Costs become arithmetic and score workspace.

Reconstruct

Why does a one-row upper-triangular mask fail during cached decoding?

Reasoned answer

It treats the query as position zero and hides every key column after zero, even when those keys are historical. Build visibility from absolute positions and separately exclude invalid cached entries when padding is present. An all-false row is rejected rather than evaluated as negative-infinity minus negative-infinity.