An attention-only transformer keeps one residual vector per position and every head adds to it. Implement the forward pass so that it also returns what each component wrote, then attribute a logit difference to the components.
attn_only_forward(tokens, W)
tokens is a list of token ids. W is a dict with "W_E" (V, d), "W_pos" (T_max, d), "W_U" (d, V) and "layers", a list of layers; each layer is a list of heads and each head is a dict with "W_Q", "W_K", "W_V" of shape (d, d_h) and "W_O" of shape (d_h, d).W_E[tokens] + W_pos[:T]. In each layer every head reads the same layer-input residual: scores (x W_Q)(x W_K)^T / sqrt(d_h), a causal mask (position attends to ) applied as , row softmax, output (A (x W_V)) W_O. The layer's output residual is the input plus the sum of its heads' outputs. No layernorm, no MLP.(residual, writes) where residual is the final (T, d) array and writes is a dict mapping "embed" to the initial residual and ("head", layer, head) to that head's (T, d) output.direct_logit_attribution(writes, W_U, tok_a, tok_b, pos=-1)
pos is with the columns of W_U. Return a dict mapping each key of writes to its contribution , as Python floats rounded to 6 decimals. The contributions must sum to the full logit difference.np.triu(np.ones((T, T)), 1) and set those entries to a very negative number before the softmax.