Implement a basic version of a transformer's self-attention mechanism from scratch.
Implement scaled dot-product attention for query, key, and value matrices represented as nested lists. Return the attention output, applying an optional boolean mask where False entries are excluded. Use a numerically stable softmax and scale scores by the key dimension.
def self_attention(query, key, value, mask=None):