openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / workloads / attention / reference.py
| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | """Single-head causal attention O = softmax(mask(Q K^T * 0.125)) V, with the elementwise error bound. |
| 3 | |
| 4 | The bound (see workload.json "why") is computed per element, so the scale returned for "o" is the |
| 5 | whole bound and the manifest uses rtol 1. Notation for row i, n = i + 1 unmasked columns j: |
| 6 | s_j = 0.125 sum_c q_c k_jc (exact), a_j = 0.125 sum_c |q_c k_jc|, e_j = gamma(Dh) a_j, E = max_j e_j, |
| 7 | d_j = s_j - max s, p_j = exp(d_j) / sum exp(d), tau_j = e_j + E + u (|d_j| + e_j + E), |
| 8 | theta_j = exp(tau_j) (1 + EXP) - 1 relative error of each exp(score - max) |
| 9 | K = sum_j p_j ((1 + theta_j)(1 + gamma(n - 1)) - 1) relative error of the softmax denominator |
| 10 | c_j = (1 + theta_j)(1 + gamma(n + 1))(1 + u) / (1 - K) - 1 |
| 11 | bound_ic = sum_j p_j |v_jc| c_j |
| 12 | """ |
| 13 | import numpy as np |
| 14 | |
| 15 | U = 2.0 ** -24 |
| 16 | EXP = 6.0 * U # OpenCL exp <= 3 ulp (OpenCL C 3.0 s7.4); 1 ulp <= 2u relative, so <= 6u |
| 17 | |
| 18 | |
| 19 | def _gamma(n): |
| 20 | return n * U / (1.0 - n * U) |
| 21 | |
| 22 | |
| 23 | def reference(p, x): |
| 24 | t, d = p["T"], p["Dh"] |
| 25 | q = x["q"].astype(np.float64).reshape(t, d) |
| 26 | k = x["k"].astype(np.float64).reshape(t, d) |
| 27 | v = x["v"].astype(np.float64).reshape(t, d) |
| 28 | s_all = 0.125 * (q @ k.T) |
| 29 | a_all = 0.125 * (np.abs(q) @ np.abs(k).T) |
| 30 | g = _gamma(d) |
| 31 | o = np.zeros((t, d)) |
| 32 | bound = np.zeros((t, d)) |
| 33 | for i in range(t): |
| 34 | n = i + 1 |
| 35 | s = s_all[i, :n] |
| 36 | e = g * a_all[i, :n] |
| 37 | big_e = e.max() |
| 38 | dj = s - s.max() |
| 39 | w = np.exp(dj) |
| 40 | pj = w / w.sum() |
| 41 | tau = e + big_e + U * (np.abs(dj) + e + big_e) |
| 42 | theta = np.expm1(tau) * (1.0 + EXP) + EXP |
| 43 | kk = float(np.sum(pj * ((1.0 + theta) * (1.0 + _gamma(n - 1)) - 1.0))) |
| 44 | c = (1.0 + theta) * (1.0 + _gamma(n + 1)) * (1.0 + U) / (1.0 - kk) - 1.0 |
| 45 | o[i] = pj @ v[:n] |
| 46 | bound[i] = (pj * c) @ np.abs(v[:n]) |
| 47 | return {"o": (o, bound)} |