Frame · dsa / ai-algorithms / 18-scaled-dot-product-attention.jsJavaScript
Scaled Dot-Product Attention for a Single Query
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
Scaled Dot-Product Attention for a Single Query
Problem: Compute the attention output for one query vector, the core
operation inside every transformer layer:
scores_i = (q . k_i) / sqrt(d)
weights = softmax(scores) (masked positions get weight 0)
output = sum_i weights_i * v_i
Inputs: query q (length d), keys K (n x d), values V (n x dv) and an
optional boolean mask of length n (false = cannot attend, e.g. padding or
future tokens under a causal mask). Return `{ scores, weights, output }`.
If every position is masked, weights are all 0 and output is a zero vector.
Constraints:
- 1 <= n <= 10^4, 1 <= d, dv <= 1024
Example:
q = [1, 0], K = [[1, 0], [0, 1]], V = [[10, 0], [0, 10]]
scores = [0.7071, 0], weights ~ [0.6698, 0.3302], output ~ [6.698, 3.302]
Approach: One pass for the dot products, a max-shifted softmax for
stability (masked scores become -Infinity), then a weighted sum of the
value rows. Dividing by sqrt(d) keeps score variance near 1 so the softmax
does not saturate as d grows. Time O(n * (d + dv)), space O(n + dv).
@param {number[]} q
@param {number[][]} K
@param {number[][]} V
@param {boolean[]} [mask]
@returns {{ scores: number[], weights: number[], output: number[] }}