In the video's picture, one head of masked self-attention has four matrices: the query and key maps, and a value map factored into a value-down matrix (into the small head space) and a value-up matrix (back to the embedding space). Each head proposes a change for every token, and the block adds all heads' changes to the embeddings. Papers write the same computation with one output matrix. Implement both views.
Shapes: E is (n, d), one row per token in order. In each head, W_q, W_k and W_down are (d_head, d) and W_up is (d, d_head). A head is a dict with those four keys.
attention_head(E, W_q, W_k, W_down, W_up) returns (pattern, delta):
pattern is the softmax of each row of : row holds the weights token gives to every token. (The video draws the same grid with queries as columns.)delta is , shape (n, d): row is the change proposed for token .Return both as nested lists rounded to 4 decimals.
output_matrix(heads): the heads' W_up matrices placed side by side in head order, a NumPy array of shape (d, n_heads * d_head).
multi_head_attention(E, heads): compute each head's , concatenate them along the feature axis in head order, multiply by the output matrix (transposed), and add the result to E. Return the refined embeddings as a nested list rounded to 4 decimals.
attention_params(d_model, d_head, n_heads, n_layers): the number of attention weights, counting the four d_model x d_head matrices of every head (no biases). Return {"per_head", "per_block", "total"} as Python ints.