concept

Scaled dot-product attention

Row-wise masked weighted combination of value vectors. Q and K share key width; K and V share sequence length. Additive mask is zero for visible positions and negative infinity for blocked positions. All-masked rows require explicit handling. Teaching function uses an allow-mask instead of additive mask.

Formal Syntax & Structure

artificial-intelligence syntaxartificial-intelligence
softmax(Q K^T / sqrt(d_k) + mask) V

Working Example

Example Snippetartificial-intelligence
from math import exp, sqrt
def attention(query, keys, values, allowed):    d = len(query)    if not d or not keys or len(keys) != len(values) or len(keys) != len(allowed):        raise ValueError("invalid attention shapes")    if any(len(k) != d for k in keys):        raise ValueError("key dimension must match query")    width = len(values[0])    if not width or any(len(v) != width for v in values):        raise ValueError("value vectors must share a positive width")    if not any(allowed):        raise ValueError("at least one key must be visible")    scores = [sum(q*k for q,k in zip(query,key))/sqrt(d) for key in keys]    peak = max(s for s,ok in zip(scores,allowed) if ok)    exps = [exp(s-peak) if ok else 0.0 for s,ok in zip(scores,allowed)]    total = sum(exps)    weights = [e/total for e in exps]    context = [sum(w*v[j] for w,v in zip(weights,values)) for j in range(width)]    return weights, contextweights, context = attention([1,0], [[1,0],[0,1]], [[4,2],[8,6]], [True,True])print([round(x,3) for x in weights])print([round(x,3) for x in context])print(attention([1,0], [[1,0],[0,1]], [[4,2],[8,6]], [True,False]))