"""Inspectable scaled dot-product attention. Python 3, standard library only.
Run: python reference.py
The four-token example is illustrative, not a trained language model.
"""
import math

def attention(q, k, v, causal=False, temperature=1.0):
    if not q or not k or not v or len(k) != len(v):
        raise ValueError('Nonempty matrices and one value row per key required')
    dk, dv = len(q[0]), len(v[0])
    if dk == 0 or dv == 0 or temperature <= 0:
        raise ValueError('Dimensions and temperature must be positive')
    if any(len(row) != dk for row in q + k) or any(len(row) != dv for row in v):
        raise ValueError('Inconsistent matrix dimensions')
    outputs, distributions = [], []
    for i, query in enumerate(q):
        scores = [sum(a*b for a, b in zip(query, key))/math.sqrt(dk) for key in k]
        allowed = [not causal or j <= i for j in range(len(k))]
        if not any(allowed):
            raise ValueError('All-masked attention row')
        maximum = max(score for score, ok in zip(scores, allowed) if ok)
        exps = [math.exp((score-maximum)/temperature) if ok else 0.0
                for score, ok in zip(scores, allowed)]
        weights = [e/sum(exps) for e in exps]
        outputs.append([sum(weight*value[d] for weight, value in zip(weights, v))
                        for d in range(dv)])
        distributions.append(weights)
    return outputs, distributions

def project(x, w):
    return [[sum(row[i]*w[i][j] for i in range(len(w)))
             for j in range(len(w[0]))] for row in x]

if __name__ == '__main__':
    x = [[1, 0], [0, 1], [.8, .2], [.6, .4]]
    q = project(x, [[2, 0], [0, 1]])
    k = project(x, [[2, 0], [0, 2]])
    v = project(x, [[1, 0], [0, 1]])
    z, p = attention(q, k, v)
    assert all(abs(sum(row)-1) < 1e-12 for row in p)
    uniform, _ = attention([[0, 0]], [[1, 0], [0, 1]], [[2, 4], [6, 8]])
    assert uniform == [[4.0, 6.0]]
    masked, mask_weights = attention(q, k, v, causal=True)
    assert masked[0] == v[0] and mask_weights[0] == [1.0, 0.0, 0.0, 0.0]
    assert mask_weights[2][3] == 0
    nontrivial, _ = attention([[1, 2]], [[1, 0], [0, 1]], [[2, 4], [6, 8]])
    assert abs(nontrivial[0][0] - 4.679046197306628) < 1e-12
    print('All reference checks passed.')
    print('Query it, weights:', p[2])
    print('Query it, output: ', z[2])
