Attention and weighted context
What attention computes
Attention builds a context vector by combining value vectors with weights that depend on the current query. In language models this lets one token position use information from other positions. A simple weighted average illustrates the idea before any learned parameters: weights 0.25 and 0.75 applied to scalar values 4 and 8 give 0.25×4 + 0.75×8 = 7. The weights sum to one; the larger weight contributes more, but does not turn the smaller value into zero.
Compute a weighted context
For scalar values, context = sum(weight × value). For vectors, use the same weights independently on every component. The teaching function below accepts nonempty equal-length lists of small finite numbers, nonnegative normalized weights (within 1e-9), and no external dependencies. It rejects invalid lengths instead of silently truncating zip.
def weighted_context(weights, values): if not weights or len(weights) != len(values): raise ValueError("equal nonempty lengths required") if any(w < 0 for w in weights) or abs(sum(weights)-1) > 1e-9: raise ValueError("weights must be nonnegative and sum to one") return sum(w*v for w,v in zip(weights, values))print(weighted_context([.25,.75],[4,8]))print(weighted_context([1,0],[4,8]))Read the result
The outputs are 7.0 and 4. A weight of zero excludes that value. Equal weights produce the arithmetic mean. A normalized combination lies within the scalar minimum and maximum, or within the convex hull of vector values; a later learned projection need not preserve that bound.
Queries, keys and values
Think of a query as a vector specifying what information is useful for one output position, a key as a vector used to score a candidate position, and a value as the vector actually combined. These are learned projections of representations in a real model, not literal database fields or conscious intentions. With L query rows and S key/value rows, Q has shape L×d_k, K has shape S×d_k, V has shape S×d_v. QKᵀ has shape L×S; row-wise softmax gives L×S weights, and multiplying by V produces L×d_v. In self-attention Q, K and V are derived from the same sequence; in cross-attention Q comes from one sequence and K,V from another.
Scaled dot-product attention
For one query, score_i = dot(q,k_i)/sqrt(d_k). Scaling helps control score magnitude as dimension grows under typical initialization assumptions; it does not force any particular weight. Softmax gives exp(score_i)/sum(exp(scores)). Subtract the largest allowed score before exponentiation to avoid overflow for ordinary large finite inputs: softmax is unchanged by a common additive shift. Masked keys receive weight zero and do not enter the denominator. The function uses a single query, small finite vectors, and a Boolean allow-mask (True means visible). An all-masked query raises ValueError by explicit teaching contract; real library behavior can differ. This is not a full framework API.
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]))Interpret the numerical example
The first scores are 1/sqrt(2) and 0, yielding weights approximately [0.67, 0.33] (rounded output [0.67, 0.33]). The context is approximately [5.321, 3.321]. With the second key masked, weights are [1.0, 0.0] and context [4.0, 2.0]. The output width is the value width, not necessarily the query width. Use the same lengths for keys, values and mask; a mask does not shorten the returned weight list.
Common mistakes and practice
Do not normalize across all query rows as one array: each query has its own distribution. Do not mask after softmax without renormalizing. Do not assume a large attention weight alone proves which token caused a prediction: values, projections, other heads, residual paths and subsequent layers also influence the output. Practice: compute weights when both keys have identical scores, then mask one key and predict the resulting vector. Related concepts: linear algebra, softmax, forward propagation; next lesson: Transformer structure.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Attention and weighted context quiz
Apply the attention and transformer mental models.
What is the context for weights [0.25,0.75] and values [4,8]?
Which vectors are actually combined using attention weights?
Q is 3×4, K is 5×4 and V is 5×2. What is the context shape?
Why subtract the largest visible score before applying softmax?
A query can see only the first of two values [4,2] and [8,6]. What context results?