Compute attention rollout for a ViT
Why it matters Rollout maps are a common way to visualise what a ViT or CLIP image encoder is looking at.
Attention rollout explains which patches a ViT used by multiplying attention maps through the layers, accounting for residual connections.
Write attention_rollout(attns). attns is a list of (heads, T, T) attention arrays, one per layer from first to last. For each layer, average over heads, add the identity, renormalise rows to sum to 1. The rollout is the product A_L @ ... @ A_1 (last layer on the left). Return the (T, T) rollout matrix.
def attention_rollout(attns)Example
if every layer's attention is the identity, the rollout is the identity.
Understand the idea
Attention rollout estimates how much each output token depends on each input token across all layers of a ViT. One layer's attention only shows direct mixing, so you chain the layers together by multiplying their attention matrices. Each layer also has a residual connection that carries a token's own information forward, which is modelled by adding the identity before renormalising. Worked example: T = 2, one head, two layers, each with attention [[0, 1], [0, 1]] (both tokens look at token 1). Add I: [[1, 1], [0, 2]], normalise rows: [[0.5, 0.5], [0, 1]]. The rollout is that matrix times itself: [[0.25, 0.75], [0, 1]]. So token 0 now draws 75 percent from token 1. Rule: for each layer, A = mean over heads, A = A + I, divide each row by its sum; rollout = A_L @ ... @ A_2 @ A_1, with later layers multiplied on the left. Start from the identity and do rollout = A @ rollout for each layer in order. Multiplying on the right gives the wrong composition order. Used in: explaining ViT predictions by visualising the row of the CLS token as a heat map.
Shapes and data flow
per layer: (H, T, T) -> mean heads (T, T) -> + I -> row-normalise rollout = A_L ... A_2 A_1 (T, T)