Skip to main content
Core Pattern · Interactive Simmedium•DECEMBER 2026•10 MIN

Causal Self-Attention & KV-Cache Step: Prefill vs Decode

Scaled dot-product attention with upper-triangular -inf masking, and how KV caching turns O(t²·d) decode into O(t·d).

attentionkv-cachecausal maskllmtransformersnumpy

The problem

Given query, key, and value projections Q, K, V, compute causal self-attention where token i can only attend to positions j ≤ i. During autoregressive decoding at step t, compute the output for the single new query q_t using cached K_cache, V_cache.

Watch it run

Toggle between Prefill (4×4) and KV-Cache Decode Step (1×4) to see how caching K and V eliminates redundant matrix work while producing the exact same output vector for token 3.

LOADING CAUSAL ATTENTION & KV CACHE SIM...

Reference implementation

import numpy as np

def causal_attention(Q: np.ndarray, K: np.ndarray, V: np.ndarray) -> np.ndarray:
    t_q, d_k = Q.shape
    t_k = K.shape[0]
    scores = (Q @ K.T) / np.sqrt(d_k)
    # Works for both prefill (t_q == t_k) and decode (t_q == 1, t_k == t)
    mask = np.triu(np.ones((t_q, t_k), dtype=bool), k=t_k - t_q + 1)
    scores = np.where(mask, -np.inf, scores)
    scores -= np.max(scores, axis=-1, keepdims=True)
    weights = np.exp(scores) / np.sum(np.exp(scores), axis=-1, keepdims=True)
    return weights @ V

Related Lab Entries